Debian Codegraph @

core/shell_transport_ssh_lib.go

raw
1 package core
2
3 import (
4 "fmt"
5 "io"
6 "net"
7 "os"
8 "strings"
9 "sync"
10 "time"
11
12 "github.com/dimonomid/nerdlog/log"
13 "github.com/juju/errors"
14 "golang.org/x/crypto/ssh"
15 "golang.org/x/crypto/ssh/agent"
16 )
17
18 // ShellTransportSSHLib implements ShellTransport over SSH.
19 type ShellTransportSSHLib struct {
20 params ShellTransportSSHLibParams
21 }
22
23 var _ ShellTransport = &ShellTransportSSHLib{}
24
25 func NewShellTransportSSHLib(params ShellTransportSSHLibParams) *ShellTransportSSHLib {
26 params.Logger = params.Logger.WithNamespaceAppended("TransportSSHLib")
27
28 return &ShellTransportSSHLib{
29 params: params,
30 }
31 }
32
33 type ShellTransportSSHLibParams struct {
34 // SSHKeys specifies paths to ssh keys to try, in the given order, until
35 // an existing key is found.
36 SSHKeys []string
37
38 ConnDetails ConfigLogStreamShellTransportSSHLib
39
40 Logger *log.Logger
41 }
42
43 func (st *ShellTransportSSHLib) Connect(resCh chan<- ShellConnUpdate) {
44 go st.doConnect(resCh)
45 }
46
47 func (st *ShellTransportSSHLib) makeDebugInfo(message string) *ShellConnDebugInfo {
48 return &ShellConnDebugInfo{
49 Message: message,
50 }
51 }
52
53 func (st *ShellTransportSSHLib) doConnect(
54 resCh chan<- ShellConnUpdate,
55 ) (res ShellConnResult) {
56 logger := st.params.Logger
57
58 defer func() {
59 if res.Err != nil {
60 logger.Errorf("Connection failed: %s", res.Err)
61 }
62
63 resCh <- ShellConnUpdate{
64 Result: &res,
65 }
66 }()
67
68 connDetails := st.params.ConnDetails
69
70 resCh <- ShellConnUpdate{
71 DebugInfo: st.makeDebugInfo(fmt.Sprintf(
72 "Trying to connect using internal ssh library to addr: %s, user: %s",
73 connDetails.Host.Addr, connDetails.Host.User,
74 )),
75 }
76
77 var sshClient *ssh.Client
78
79 conf, err := st.getClientConfig(resCh, logger, connDetails.Host.User)
80 if err != nil {
81 res.Err = errors.Annotatef(err, "getting ssh client for %s", connDetails.Host.User)
82 return res
83 }
84
85 resCh <- ShellConnUpdate{
86 DebugInfo: st.makeDebugInfo(fmt.Sprintf("Got client config: %s", conf.Descr)),
87 }
88
89 if connDetails.Jumphost != nil {
90 logger.Infof("Connecting via jumphost")
91 // Use jumphost
92 jumphost, err := st.getJumphostClient(resCh, logger, connDetails.Jumphost)
93 if err != nil {
94 logger.Errorf("Jumphost connection failed: %s", err)
95 res.Err = errors.Annotatef(err, "getting jumphost client")
96 return res
97 }
98
99 conn, err := dialWithTimeout(jumphost, "tcp", connDetails.Host.Addr, connectionTimeout)
100 if err != nil {
101 res.Err = errors.Annotatef(err, conf.Descr)
102 return res
103 }
104
105 authConn, chans, reqs, err := ssh.NewClientConn(conn, connDetails.Host.Addr, conf.ClientConfig)
106 if err != nil {
107 res.Err = errors.Annotatef(err, conf.Descr)
108 return res
109 }
110
111 sshClient = ssh.NewClient(authConn, chans, reqs)
112 } else {
113 logger.Infof("Connecting to %s (%+v)", connDetails.Host.Addr, conf)
114 var err error
115 sshClient, err = ssh.Dial("tcp", connDetails.Host.Addr, conf.ClientConfig)
116 if err != nil {
117 res.Err = errors.Annotatef(err, conf.Descr)
118 return res
119 }
120 }
121
122 shellBin := "/bin/sh"
123
124 resCh <- ShellConnUpdate{
125 DebugInfo: st.makeDebugInfo(fmt.Sprintf("Connected, creating pipes and starting %s", shellBin)),
126 }
127 logger.Infof("Connected to %s", connDetails.Host.Addr)
128
129 sshSession, err := sshClient.NewSession()
130 if err != nil {
131 res.Err = errors.Annotatef(err, conf.Descr)
132 return res
133 }
134
135 stdinBuf, err := sshSession.StdinPipe()
136 if err != nil {
137 res.Err = errors.Annotatef(err, conf.Descr)
138 return res
139 }
140
141 stdoutBuf, err := sshSession.StdoutPipe()
142 if err != nil {
143 res.Err = errors.Annotatef(err, conf.Descr)
144 return res
145 }
146
147 stderrBuf, err := sshSession.StderrPipe()
148 if err != nil {
149 res.Err = errors.Annotatef(err, conf.Descr)
150 return res
151 }
152
153 err = sshSession.Start(shellBin)
154 if err != nil {
155 res.Err = errors.Annotatef(err, conf.Descr)
156 return res
157 }
158
159 res.Conn = &ShellConnSSH{
160 sshClient: sshClient,
161 sshSession: sshSession,
162
163 stdinBuf: stdinBuf,
164 stdoutBuf: stdoutBuf,
165 stderrBuf: stderrBuf,
166 }
167
168 return res
169 }
170
171 // dialWithTimeout is a hack needed to get a timeout for the ssh client.
172 // https://stackoverflow.com/questions/31554196/ssh-connection-timeout
173 //
174 // It's possible we could accomplish the same thing by using NewClient() with Conn.SetDeadline(), but that requires
175 // some refactoring.
176 func dialWithTimeout(client *ssh.Client, protocol, hostAddr string, timeout time.Duration) (net.Conn, error) {
177 finishedChan := make(chan net.Conn)
178 errChan := make(chan error)
179 go func() {
180 conn, err := client.Dial(protocol, hostAddr)
181 if err != nil {
182 errChan <- err
183 return
184 }
185 finishedChan <- conn
186 }()
187
188 select {
189 case conn := <-finishedChan:
190 return conn, nil
191
192 case err := <-errChan:
193 return nil, errors.Trace(err)
194
195 case <-time.After(connectionTimeout):
196 // Don't close the connection here since it's reused
197 return nil, errors.New("ssh client dial timed out")
198 }
199 }
200
201 type ClientConfigWMeta struct {
202 // ClientConfig is the actual client config.
203 ClientConfig *ssh.ClientConfig
204
205 // Descr is a human-readable string which is useful to include in any
206 // error messages about this SSH connection.
207 Descr string
208 }
209
210 type AuthMethodWMeta struct {
211 AuthMethod ssh.AuthMethod
212
213 // Descr is a human-readable string which is useful to include in any
214 // error messages about this SSH connection.
215 Descr string
216 }
217
218 func (st *ShellTransportSSHLib) getClientConfig(resCh chan<- ShellConnUpdate, logger *log.Logger, username string) (*ClientConfigWMeta, error) {
219 auth, err := st.getSSHAuthMethod(resCh, logger)
220 if err != nil {
221 return nil, errors.Trace(err)
222 }
223
224 return &ClientConfigWMeta{
225 ClientConfig: &ssh.ClientConfig{
226 User: username,
227 Auth: []ssh.AuthMethod{auth.AuthMethod},
228
229 // TODO: fix it
230 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
231
232 Timeout: connectionTimeout,
233 },
234 Descr: auth.Descr,
235 }, nil
236 }
237
238 var (
239 sshAuthMethodShared *AuthMethodWMeta
240 sshAuthMethodSharedMtx sync.Mutex
241 )
242
243 func (st *ShellTransportSSHLib) getSSHAuthMethod(resCh chan<- ShellConnUpdate, logger *log.Logger) (*AuthMethodWMeta, error) {
244 sshAuthMethodSharedMtx.Lock()
245 defer sshAuthMethodSharedMtx.Unlock()
246
247 if sshAuthMethodShared != nil {
248 return sshAuthMethodShared, nil
249 }
250
251 // Try ssh-agent first
252 var sshAgentErr error
253 sshAuthSock := os.Getenv("SSH_AUTH_SOCK")
254 if sshAuthSock != "" {
255 logger.Infof("Trying ssh-agent via SSH_AUTH_SOCK=%s", sshAuthSock)
256 sshAgent, err := net.Dial("unix", sshAuthSock)
257 if err != nil {
258 logger.Infof("Failed to connect to ssh-agent: %s", err.Error())
259 sshAgentErr = errors.Annotatef(err, "using SSH_AUTH_SOCK env var")
260 } else {
261 sshAuthMethodShared = &AuthMethodWMeta{
262 AuthMethod: ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
263 Descr: "using ssh-agent",
264 }
265 return sshAuthMethodShared, nil
266 }
267 } else {
268 sshAgentErr = errors.Errorf("SSH_AUTH_SOCK env var is empty")
269 logger.Infof("SSH_AUTH_SOCK not set; skipping ssh-agent")
270 }
271
272 // Fall back to private key
273 logger.Infof("Fallback to parsing ssh key...")
274
275 var keyPath string
276 var keyData []byte
277 var errBuilder strings.Builder
278 for _, keyPath = range st.params.SSHKeys {
279 var err error
280 keyData, err = os.ReadFile(keyPath)
281 if err != nil {
282 if errBuilder.Len() > 0 {
283 errBuilder.WriteString(", ")
284 }
285 errBuilder.WriteString(fmt.Sprintf("%s: %s", keyPath, err.Error()))
286 continue
287 }
288
289 // Found the key file.
290 break
291 }
292
293 if len(keyData) == 0 {
294 return nil, errors.Errorf(
295 "failed to read key data from any of the following: %s (%s)",
296 st.params.SSHKeys,
297 errBuilder.String(),
298 )
299 }
300
301 signer, err := ssh.ParsePrivateKey(keyData)
302 if err != nil {
303 if _, ok := err.(*ssh.PassphraseMissingError); ok {
304 // We need a passphrase to decrypt the private key. Request it from
305 // the client code.
306 passphraseCh := make(chan string, 1)
307
308 resCh <- ShellConnUpdate{
309 DataRequest: &ShellConnDataRequest{
310 Title: "SSH key is passphrase-protected",
311 Message: fmt.Sprintf("Unable to use ssh-agent: %s, falling back to ssh keys.\nPlease enter passphrase for %s.\nAlternatively, use ssh-agent, and make sure the SSH_AUTH_SOCK environment variable is set correctly.\nTo use a different ssh key, provide it with the --ssh-key flag.", sshAgentErr.Error(), keyPath),
312 DataKind: ShellConnDataKindPassword,
313 ResponseCh: passphraseCh,
314 },
315 }
316
317 // Now wait for the client code to provide the passphrase.
318 //
319 // TODO: support teardown; as of now, if the user tries to exit the app,
320 // it'll be stuck on the "Closing connections" stage, until the Ctrl+C is
321 // pressed.
322 passphrase := <-passphraseCh
323
324 var err error
325 signer, err = ssh.ParsePrivateKeyWithPassphrase(keyData, []byte(passphrase))
326 if err != nil {
327 // Something has failed even with the provided passphrase.
328 // We don't implement any retries here in case of typos, because the
329 // whole connection will be retried, and we'll naturally ask for the
330 // passphrase again.
331 return nil, errors.Annotatef(err, "parsing private key from %s with the given passphrase", keyPath)
332 }
333 } else {
334 return nil, errors.Annotatef(err, "parsing private key from %s", keyPath)
335 }
336 }
337
338 logger.Infof("Using private key from %s", keyPath)
339 sshAuthMethodShared = &AuthMethodWMeta{
340 AuthMethod: ssh.PublicKeys(signer),
341 Descr: fmt.Sprintf("using key %s", keyPath),
342 }
343 return sshAuthMethodShared, nil
344 }
345
346 var (
347 jumphostsShared = map[string]*ssh.Client{}
348 jumphostsSharedMtx sync.Mutex
349 )
350
351 func (st *ShellTransportSSHLib) getJumphostClient(resCh chan<- ShellConnUpdate, logger *log.Logger, jhConfig *ConfigHost) (*ssh.Client, error) {
352 jumphostsSharedMtx.Lock()
353 defer jumphostsSharedMtx.Unlock()
354
355 key := jhConfig.Key()
356 jh := jumphostsShared[key]
357 if jh == nil {
358 logger.Infof("Connecting to jumphost... %+v", jhConfig)
359
360 parts := strings.Split(jhConfig.Addr, ":")
361 if len(parts) != 2 {
362 return nil, errors.Errorf("malformed jumphost address %q", jhConfig.Addr)
363 }
364
365 addrs, err := net.LookupHost(parts[0])
366 if err != nil {
367 return nil, errors.Trace(err)
368 }
369
370 if len(addrs) != 1 {
371 return nil, errors.New("Address not found")
372 }
373
374 conf, err := st.getClientConfig(resCh, logger, jhConfig.User)
375 if err != nil {
376 return nil, errors.Trace(err)
377 }
378
379 jh, err = ssh.Dial("tcp", jhConfig.Addr, conf.ClientConfig)
380 if err != nil {
381 return nil, errors.Trace(err)
382 }
383
384 jumphostsShared[key] = jh
385
386 logger.Infof("Jumphost ok")
387 }
388
389 return jh, nil
390 }
391
392 // ShellConnSSH implements ShellConn for SSH.
393 type ShellConnSSH struct {
394 sshClient *ssh.Client
395 sshSession *ssh.Session
396
397 stdinBuf io.WriteCloser
398 stdoutBuf io.Reader
399 stderrBuf io.Reader
400 }
401
402 var _ ShellConn = &ShellConnSSH{}
403
404 func (c *ShellConnSSH) Stdin() io.Writer {
405 return c.stdinBuf
406 }
407
408 func (c *ShellConnSSH) Stdout() io.Reader {
409 return c.stdoutBuf
410 }
411
412 func (c *ShellConnSSH) Stderr() io.Reader {
413 return c.stderrBuf
414 }
415
416 // Close closes underlying SSH connection.
417 func (c *ShellConnSSH) Close() {
418 c.stdinBuf.Close()
419 c.sshSession.Close()
420 c.sshClient.Close()
421 }