blob: d0a051840953065b69b707dafbe4d5dbff2eac2c [file] [log] [blame]
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +01001package ssh
Serge Bazanskicaa12082023-02-16 14:54:04 +01002
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "net"
9 "time"
10
11 "github.com/pkg/sftp"
12 "golang.org/x/crypto/ssh"
13)
14
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010015// Client defines a simple interface to an abstract SSH client. Usually this
16// would be DirectClient, but tests can use this interface to dependency-inject
Serge Bazanskicaa12082023-02-16 14:54:04 +010017// fake SSH connections.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010018type Client interface {
19 // Dial returns an Connection to a given address (host:port pair) with
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020020 // a timeout for connection.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010021 Dial(ctx context.Context, address string, connectTimeout time.Duration) (Connection, error)
Serge Bazanskicaa12082023-02-16 14:54:04 +010022}
23
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010024type Connection interface {
Serge Bazanskicaa12082023-02-16 14:54:04 +010025 // Execute a given command on a remote host synchronously, passing in stdin as
26 // input, and returning a captured stdout/stderr. The returned data might be
27 // valid even when err != nil, which might happen if the remote side returned a
28 // non-zero exit code.
29 Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error)
30 // Upload a given blob to a targetPath on the system and make executable.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010031 Upload(ctx context.Context, targetPath string, src io.Reader) error
Serge Bazanskicaa12082023-02-16 14:54:04 +010032 // Close this connection.
33 Close() error
34}
35
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010036// DirectClient implements Client (and Connection) using
Serge Bazanskicaa12082023-02-16 14:54:04 +010037// golang.org/x/crypto/ssh.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010038type DirectClient struct {
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020039 AuthMethods []ssh.AuthMethod
40 Username string
Serge Bazanskicaa12082023-02-16 14:54:04 +010041}
42
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010043type directConn struct {
Serge Bazanskicaa12082023-02-16 14:54:04 +010044 cl *ssh.Client
45}
46
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010047func (p *DirectClient) Dial(ctx context.Context, address string, connectTimeout time.Duration) (Connection, error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010048 d := net.Dialer{
49 Timeout: connectTimeout,
50 }
51 conn, err := d.DialContext(ctx, "tcp", address)
52 if err != nil {
53 return nil, err
54 }
55 conf := &ssh.ClientConfig{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020056 User: p.Username,
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020057 Auth: p.AuthMethods,
Serge Bazanskicaa12082023-02-16 14:54:04 +010058 // Ignore the host key, since it's likely the first time anything logs into
59 // this device, and also because there's no way of knowing its fingerprint.
60 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
61 // Timeout sets a bound on the time it takes to set up the connection, but
62 // not on total session time.
63 Timeout: connectTimeout,
64 }
65 conn2, chanC, reqC, err := ssh.NewClientConn(conn, address, conf)
66 if err != nil {
67 return nil, err
68 }
69 cl := ssh.NewClient(conn2, chanC, reqC)
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010070 return &directConn{
Serge Bazanskicaa12082023-02-16 14:54:04 +010071 cl: cl,
72 }, nil
73}
74
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010075func (p *directConn) Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010076 sess, err := p.cl.NewSession()
77 if err != nil {
78 return nil, nil, fmt.Errorf("while creating SSH session: %w", err)
79 }
80 stdoutBuf := bytes.NewBuffer(nil)
81 stderrBuf := bytes.NewBuffer(nil)
82 sess.Stdin = bytes.NewBuffer(stdin)
83 sess.Stdout = stdoutBuf
84 sess.Stderr = stderrBuf
85 defer sess.Close()
86
87 if err := sess.Start(command); err != nil {
88 return nil, nil, err
89 }
90 doneC := make(chan error, 1)
91 go func() {
92 doneC <- sess.Wait()
93 }()
94 select {
95 case <-ctx.Done():
96 return nil, nil, ctx.Err()
97 case err := <-doneC:
98 return stdoutBuf.Bytes(), stderrBuf.Bytes(), err
99 }
100}
101
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100102func (p *directConn) Upload(ctx context.Context, targetPath string, src io.Reader) error {
Lorenz Brunc5d28e42024-09-17 20:38:31 +0200103 sc, err := sftp.NewClient(p.cl, sftp.UseConcurrentWrites(true), sftp.MaxConcurrentRequestsPerFile(1024))
Serge Bazanskicaa12082023-02-16 14:54:04 +0100104 if err != nil {
105 return fmt.Errorf("while building sftp client: %w", err)
106 }
107 defer sc.Close()
108
Serge Bazanskicaa12082023-02-16 14:54:04 +0100109 df, err := sc.Create(targetPath)
110 if err != nil {
111 return fmt.Errorf("while creating file on the host: %w", err)
112 }
113
114 doneC := make(chan error, 1)
115
116 go func() {
Lorenz Brunc5d28e42024-09-17 20:38:31 +0200117 _, err := df.ReadFromWithConcurrency(src, 0)
Serge Bazanskicaa12082023-02-16 14:54:04 +0100118 df.Close()
119 doneC <- err
120 }()
121
122 select {
123 case err := <-doneC:
124 if err != nil {
125 return fmt.Errorf("while copying file: %w", err)
126 }
127 case <-ctx.Done():
128 df.Close()
129 return ctx.Err()
130 }
131
132 if err := sc.Chmod(targetPath, 0755); err != nil {
133 return fmt.Errorf("while setting file permissions: %w", err)
134 }
135 return nil
136}
137
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100138func (p *directConn) Close() error {
Serge Bazanskicaa12082023-02-16 14:54:04 +0100139 return p.cl.Close()
140}