blob: 4e3cab684fff6eb91b2fc0cf3dbbf3d1338b45c8 [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 Windelschmidtb6308cd2023-10-10 21:19:03 +020039 AuthMethod 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,
Serge Bazanskicaa12082023-02-16 14:54:04 +010057 Auth: []ssh.AuthMethod{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020058 p.AuthMethod,
Serge Bazanskicaa12082023-02-16 14:54:04 +010059 },
60 // Ignore the host key, since it's likely the first time anything logs into
61 // this device, and also because there's no way of knowing its fingerprint.
62 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
63 // Timeout sets a bound on the time it takes to set up the connection, but
64 // not on total session time.
65 Timeout: connectTimeout,
66 }
67 conn2, chanC, reqC, err := ssh.NewClientConn(conn, address, conf)
68 if err != nil {
69 return nil, err
70 }
71 cl := ssh.NewClient(conn2, chanC, reqC)
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010072 return &directConn{
Serge Bazanskicaa12082023-02-16 14:54:04 +010073 cl: cl,
74 }, nil
75}
76
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010077func (p *directConn) Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010078 sess, err := p.cl.NewSession()
79 if err != nil {
80 return nil, nil, fmt.Errorf("while creating SSH session: %w", err)
81 }
82 stdoutBuf := bytes.NewBuffer(nil)
83 stderrBuf := bytes.NewBuffer(nil)
84 sess.Stdin = bytes.NewBuffer(stdin)
85 sess.Stdout = stdoutBuf
86 sess.Stderr = stderrBuf
87 defer sess.Close()
88
89 if err := sess.Start(command); err != nil {
90 return nil, nil, err
91 }
92 doneC := make(chan error, 1)
93 go func() {
94 doneC <- sess.Wait()
95 }()
96 select {
97 case <-ctx.Done():
98 return nil, nil, ctx.Err()
99 case err := <-doneC:
100 return stdoutBuf.Bytes(), stderrBuf.Bytes(), err
101 }
102}
103
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100104func (p *directConn) Upload(ctx context.Context, targetPath string, src io.Reader) error {
Serge Bazanskicaa12082023-02-16 14:54:04 +0100105 sc, err := sftp.NewClient(p.cl)
106 if err != nil {
107 return fmt.Errorf("while building sftp client: %w", err)
108 }
109 defer sc.Close()
110
Serge Bazanskicaa12082023-02-16 14:54:04 +0100111 df, err := sc.Create(targetPath)
112 if err != nil {
113 return fmt.Errorf("while creating file on the host: %w", err)
114 }
115
116 doneC := make(chan error, 1)
117
118 go func() {
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100119 _, err := io.Copy(df, src)
Serge Bazanskicaa12082023-02-16 14:54:04 +0100120 df.Close()
121 doneC <- err
122 }()
123
124 select {
125 case err := <-doneC:
126 if err != nil {
127 return fmt.Errorf("while copying file: %w", err)
128 }
129 case <-ctx.Done():
130 df.Close()
131 return ctx.Err()
132 }
133
134 if err := sc.Chmod(targetPath, 0755); err != nil {
135 return fmt.Errorf("while setting file permissions: %w", err)
136 }
137 return nil
138}
139
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100140func (p *directConn) Close() error {
Serge Bazanskicaa12082023-02-16 14:54:04 +0100141 return p.cl.Close()
142}