forked from loft-sh/devpod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.go
520 lines (455 loc) · 14.9 KB
/
ssh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package cmd
import (
"context"
"encoding/base64"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/loft-sh/devpod/cmd/flags"
"github.com/loft-sh/devpod/cmd/machine"
"github.com/loft-sh/devpod/pkg/agent"
client2 "github.com/loft-sh/devpod/pkg/client"
"github.com/loft-sh/devpod/pkg/config"
"github.com/loft-sh/devpod/pkg/gpg"
"github.com/loft-sh/devpod/pkg/port"
devssh "github.com/loft-sh/devpod/pkg/ssh"
"github.com/loft-sh/devpod/pkg/tunnel"
workspace2 "github.com/loft-sh/devpod/pkg/workspace"
"github.com/loft-sh/log"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
)
// SSHCmd holds the ssh cmd flags
type SSHCmd struct {
*flags.GlobalFlags
ForwardPortsTimeout string
ForwardPorts []string
ReverseForwardPorts []string
Stdio bool
JumpContainer bool
AgentForwarding bool
GPGAgentForwarding bool
StartServices bool
Proxy bool
Command string
User string
WorkDir string
}
// NewSSHCmd creates a new ssh command
func NewSSHCmd(flags *flags.GlobalFlags) *cobra.Command {
cmd := &SSHCmd{
GlobalFlags: flags,
}
sshCmd := &cobra.Command{
Use: "ssh",
Short: "Starts a new ssh session to a workspace",
RunE: func(_ *cobra.Command, args []string) error {
ctx := context.Background()
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
client, err := workspace2.GetWorkspace(devPodConfig, args, true, log.Default.ErrorStreamOnly())
if err != nil {
return err
}
return cmd.Run(ctx, devPodConfig, client, log.Default.ErrorStreamOnly())
},
}
sshCmd.Flags().StringArrayVarP(&cmd.ForwardPorts, "forward-ports", "L", []string{}, "Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side.")
sshCmd.Flags().StringArrayVarP(&cmd.ReverseForwardPorts, "reverse-forward-ports", "R", []string{}, "Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be reverse forwarded to the given host and port, or Unix socket, on the remote side.")
sshCmd.Flags().StringVar(&cmd.ForwardPortsTimeout, "forward-ports-timeout", "", "Specifies the timeout after which the command should terminate when the ports are unused.")
sshCmd.Flags().StringVar(&cmd.Command, "command", "", "The command to execute within the workspace")
sshCmd.Flags().StringVar(&cmd.User, "user", "", "The user of the workspace to use")
sshCmd.Flags().StringVar(&cmd.WorkDir, "workdir", "", "The working directory in the container")
sshCmd.Flags().BoolVar(&cmd.Proxy, "proxy", false, "If true will act as intermediate proxy for a proxy provider")
sshCmd.Flags().BoolVar(&cmd.AgentForwarding, "agent-forwarding", true, "If true forward the local ssh keys to the remote machine")
sshCmd.Flags().BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false, "If true forward the local gpg-agent to the remote machine")
sshCmd.Flags().BoolVar(&cmd.Stdio, "stdio", false, "If true will tunnel connection through stdout and stdin")
sshCmd.Flags().BoolVar(&cmd.StartServices, "start-services", true, "If false will not start any port-forwarding or git / docker credentials helper")
return sshCmd
}
// Run runs the command logic
func (cmd *SSHCmd) Run(ctx context.Context, devPodConfig *config.Config, client client2.BaseWorkspaceClient, log log.Logger) error {
// add ssh keys to agent
if !cmd.Proxy && devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == "true" && devPodConfig.ContextOption(config.ContextOptionSSHAddPrivateKeys) == "true" {
log.Debug("Adding ssh keys to agent, disable via 'devpod context set-options -o SSH_ADD_PRIVATE_KEYS=false'")
err := devssh.AddPrivateKeysToAgent(ctx, log)
if err != nil {
log.Debugf("Error adding private keys to ssh-agent: %v", err)
}
}
// get user
if cmd.User == "" {
var err error
cmd.User, err = devssh.GetUser(client.WorkspaceConfig().ID, client.WorkspaceConfig().SSHConfigPath)
if err != nil {
return err
}
}
// set default context if needed
if cmd.Context == "" {
cmd.Context = devPodConfig.DefaultContext
}
// check if regular workspace client
workspaceClient, ok := client.(client2.WorkspaceClient)
if ok {
return cmd.jumpContainer(ctx, devPodConfig, workspaceClient, log)
}
// check if proxy client
proxyClient, ok := client.(client2.ProxyClient)
if ok {
return cmd.startProxyTunnel(ctx, devPodConfig, proxyClient, log)
}
return nil
}
func (cmd *SSHCmd) startProxyTunnel(
ctx context.Context,
devPodConfig *config.Config,
client client2.ProxyClient,
log log.Logger,
) error {
log.Debugf("Start proxy tunnel")
return tunnel.NewTunnel(
ctx,
func(ctx context.Context, stdin io.Reader, stdout io.Writer) error {
return client.Ssh(ctx, client2.SshOptions{
Stdin: stdin,
Stdout: stdout,
})
},
func(ctx context.Context, containerClient *ssh.Client) error {
return cmd.startTunnel(ctx, devPodConfig, containerClient, client.Workspace(), client.WorkspaceConfig().IDE.Name, log)
},
)
}
func startWait(
ctx context.Context,
client client2.WorkspaceClient,
create bool,
log log.Logger,
) error {
startWaiting := time.Now()
for {
instanceStatus, err := client.Status(ctx, client2.StatusOptions{})
if err != nil {
return err
} else if instanceStatus == client2.StatusBusy {
if time.Since(startWaiting) > time.Second*10 {
log.Infof("Waiting for workspace to come up...")
log.Debugf("Got status %s, expected: Running", instanceStatus)
startWaiting = time.Now()
}
time.Sleep(time.Second * 2)
continue
} else if instanceStatus == client2.StatusStopped {
if create {
// start environment
err = client.Start(ctx, client2.StartOptions{})
if err != nil {
return errors.Wrap(err, "start workspace")
}
} else {
return fmt.Errorf("DevPod workspace is stopped")
}
} else if instanceStatus == client2.StatusNotFound {
if create {
// create environment
err = client.Create(ctx, client2.CreateOptions{})
if err != nil {
return err
}
} else {
return fmt.Errorf("DevPod workspace wasn't found")
}
}
return nil
}
}
func (cmd *SSHCmd) jumpContainer(
ctx context.Context,
devPodConfig *config.Config,
client client2.WorkspaceClient,
log log.Logger,
) error {
// lock the workspace as long as we init the connection
unlockOnce := sync.Once{}
err := client.Lock(ctx)
if err != nil {
return err
}
defer unlockOnce.Do(client.Unlock)
// start the workspace
err = startWait(ctx, client, false, log)
if err != nil {
return err
}
// tunnel to container
return tunnel.NewContainerTunnel(client, cmd.Proxy, log).
Run(ctx, func(ctx context.Context, containerClient *ssh.Client) error {
// we have a connection to the container, make sure others can connect as well
unlockOnce.Do(client.Unlock)
// start ssh tunnel
return cmd.startTunnel(ctx, devPodConfig, containerClient, client.Workspace(), client.WorkspaceConfig().IDE.Name, log)
})
}
func (cmd *SSHCmd) forwardTimeout(log log.Logger) (time.Duration, error) {
timeout := time.Duration(0)
if cmd.ForwardPortsTimeout != "" {
timeout, err := time.ParseDuration(cmd.ForwardPortsTimeout)
if err != nil {
return timeout, fmt.Errorf("parse forward ports timeout: %w", err)
}
log.Infof("Using port forwarding timeout of %s", cmd.ForwardPortsTimeout)
}
return timeout, nil
}
func (cmd *SSHCmd) reverseForwardPorts(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
timeout, err := cmd.forwardTimeout(log)
if err != nil {
return fmt.Errorf("parse forward ports timeout: %w", err)
}
errChan := make(chan error, len(cmd.ReverseForwardPorts))
for _, portMapping := range cmd.ReverseForwardPorts {
mapping, err := port.ParsePortSpec(portMapping)
if err != nil {
return fmt.Errorf("parse port mapping: %w", err)
}
// start the forwarding
log.Infof(
"Reverse forwarding local %s/%s to remote %s/%s",
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
)
go func(portMapping string) {
err := devssh.ReversePortForward(
ctx,
containerClient,
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
timeout,
log,
)
if err != nil {
errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
}
}(portMapping)
}
return <-errChan
}
func (cmd *SSHCmd) forwardPorts(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
timeout, err := cmd.forwardTimeout(log)
if err != nil {
return fmt.Errorf("parse forward ports timeout: %w", err)
}
errChan := make(chan error, len(cmd.ForwardPorts))
for _, portMapping := range cmd.ForwardPorts {
mapping, err := port.ParsePortSpec(portMapping)
if err != nil {
return fmt.Errorf("parse port mapping: %w", err)
}
// start the forwarding
log.Infof(
"Forwarding local %s/%s to remote %s/%s",
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
)
go func(portMapping string) {
err := devssh.PortForward(
ctx,
containerClient,
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
timeout,
log,
)
if err != nil {
errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
}
}(portMapping)
}
return <-errChan
}
func (cmd *SSHCmd) startTunnel(ctx context.Context, devPodConfig *config.Config, containerClient *ssh.Client, workspaceName string, ideName string, log log.Logger) error {
// check if we should forward ports
if len(cmd.ForwardPorts) > 0 {
return cmd.forwardPorts(ctx, containerClient, log)
}
// check if we should reverse forward ports
if len(cmd.ReverseForwardPorts) > 0 && !cmd.GPGAgentForwarding {
return cmd.reverseForwardPorts(ctx, containerClient, log)
}
// start port-forwarding etc.
if !cmd.Proxy && cmd.StartServices {
go cmd.startServices(ctx, devPodConfig, containerClient, ideName, log)
}
// start ssh
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer writer.Close()
// check if we should do gpg agent forwarding
if cmd.GPGAgentForwarding || devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == "true" {
// Check if a forwarding is already enabled and running, in that case
// we skip the forwarding and keep using the original one
if gpg.IsGpgTunnelRunning(cmd.User, ctx, containerClient, log) {
log.Debugf("gpg: exporting already running, skipping")
} else {
err := cmd.setupGPGAgent(ctx, containerClient, log)
if err != nil {
return err
}
}
}
workdir := filepath.Join("/workspaces", workspaceName)
if cmd.WorkDir != "" {
workdir = cmd.WorkDir
}
log.Debugf("Run outer container tunnel")
command := fmt.Sprintf("'%s' helper ssh-server --track-activity --stdio --workdir '%s'", agent.ContainerDevPodHelperLocation, workdir)
if cmd.Debug {
command += " --debug"
}
if cmd.User != "" && cmd.User != "root" {
command = fmt.Sprintf("su -c \"%s\" '%s'", command, cmd.User)
}
if cmd.Proxy || cmd.Stdio {
return devssh.Run(ctx, containerClient, command, os.Stdin, os.Stdout, writer)
}
return machine.StartSSHSession(
ctx,
cmd.User,
cmd.Command,
!cmd.Proxy && cmd.AgentForwarding &&
devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == "true",
func(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
return devssh.Run(ctx, containerClient, command, stdin, stdout, stderr)
},
writer,
)
}
func (cmd *SSHCmd) startServices(
ctx context.Context,
devPodConfig *config.Config,
containerClient *ssh.Client,
ideName string,
log log.Logger,
) {
if cmd.User != "" {
gitCredentials := ideName != string(config.IDEVSCode)
err := tunnel.RunInContainer(
ctx,
devPodConfig,
containerClient,
cmd.User,
false,
gitCredentials,
true,
nil,
log,
)
if err != nil {
log.Debugf("Error running credential server: %v", err)
}
}
}
// setupGPGAgent will forward a local gpg-agent into the remote container
// this works by using cmd/agent/workspace/setup_gpg
func (cmd *SSHCmd) setupGPGAgent(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer writer.Close()
log.Debugf("gpg: exporting gpg public key from host")
// Read the user's public keys and ownertrust from GPG.
// These commands are executed LOCALLY, the output will be imported by the remote gpg
pubKeyExport, err := gpg.GetHostPubKey()
if err != nil {
return fmt.Errorf("export local public keys from GPG: %w", err)
}
log.Debugf("gpg: exporting gpg owner trust from host")
ownerTrustExport, err := gpg.GetHostOwnerTrust()
if err != nil {
return fmt.Errorf("export local ownertrust from GPG: %w", err)
}
log.Debugf("gpg: detecting gpg-agent socket path on host")
// Detect local agent extra socket, this will be forwarded to the remote and
// symlinked in multiple paths
gpgExtraSocketBytes, err := exec.Command("gpgconf", []string{"--list-dir", "agent-extra-socket"}...).
Output()
if err != nil {
return err
}
gpgExtraSocketPath := strings.TrimSpace(string(gpgExtraSocketBytes))
log.Debugf("gpg: detected gpg-agent socket path %s", gpgExtraSocketPath)
gitGpgKey, err := exec.Command("git", []string{"config", "user.signingKey"}...).Output()
if err != nil {
log.Debugf("gpg: no git signkey detected, skipping")
}
log.Debugf("gpg: detected git sign key %s", gitGpgKey)
log.Debugf("ssh: starting reverse forwarding socket %s", gpgExtraSocketPath)
cmd.ReverseForwardPorts = append(cmd.ReverseForwardPorts, gpgExtraSocketPath)
go func() {
err := cmd.reverseForwardPorts(ctx, containerClient, log)
if err != nil {
log.Fatal(err)
}
}()
pubKeyArgument := base64.StdEncoding.EncodeToString(pubKeyExport)
ownerTrustArgument := base64.StdEncoding.EncodeToString(ownerTrustExport)
// Now we forward the agent socket to the remote, and setup remote gpg to use it
// fix eventual permissions and so on
forwardAgent := []string{
agent.ContainerDevPodHelperLocation,
}
if log.GetLevel() == logrus.DebugLevel {
forwardAgent = append(forwardAgent, "--debug")
}
forwardAgent = append(forwardAgent, []string{
"agent",
"workspace",
"setup-gpg",
"--publickey",
pubKeyArgument,
"--ownertrust",
ownerTrustArgument,
"--socketpath",
gpgExtraSocketPath,
}...)
if len(gitGpgKey) > 0 {
forwardAgent = append(forwardAgent, "--gitkey")
forwardAgent = append(forwardAgent, string(gitGpgKey))
}
log.Debugf(
"gpg: start reverse forward of gpg-agent socket %s, keeping connection open",
gpgExtraSocketPath,
)
command := strings.Join(forwardAgent, " ")
if cmd.User != "" && cmd.User != "root" {
command = fmt.Sprintf("su -c \"%s\" '%s'", command, cmd.User)
}
return devssh.Run(ctx, containerClient, command, nil, writer, writer)
}