-
Notifications
You must be signed in to change notification settings - Fork 9
/
ssh.go
219 lines (180 loc) · 5.11 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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cluster
import (
"context"
"errors"
"fmt"
"net"
"os"
"os/signal"
"strings"
"syscall"
c "github.com/containerd/console"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/term"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
con "namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/providers/nscloud/api"
)
func NewSshCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "ssh [cluster-id] [command]",
Short: "Start an SSH session.",
Args: cobra.ArbitraryArgs,
}
tag := cmd.Flags().String("unique_tag", "", "If specified, creates a cluster with the specified unique tag.")
sshAgent := cmd.Flags().BoolP("ssh_agent", "A", false, "If specified, forwards the local SSH agent.")
cmd.RunE = fncobra.RunE(func(ctx context.Context, args []string) error {
if *tag != "" {
opts := api.CreateClusterOpts{
KeepAtExit: true,
Purpose: fmt.Sprintf("Manually created for ssh (%s)", *tag),
UniqueTag: *tag,
WaitClusterOpts: api.WaitClusterOpts{WaitForService: "ssh", WaitKind: "kubernetes"},
}
cluster, err := api.CreateAndWaitCluster(ctx, api.Methods, opts)
if err != nil {
return err
}
return inlineSsh(ctx, cluster.Cluster, *sshAgent, args)
}
cluster, args, err := selectRunningCluster(ctx, args)
if err != nil {
if errors.Is(err, ErrEmptyClusterList) {
printCreateClusterMsg(ctx)
return nil
}
return err
}
if cluster == nil {
return nil
}
return inlineSsh(ctx, cluster, *sshAgent, args)
})
return cmd
}
func withSsh(ctx context.Context, cluster *api.KubernetesCluster, callback func(context.Context, *ssh.Client) error) error {
sshSvc := api.ClusterService(cluster, "ssh")
if sshSvc == nil || sshSvc.Endpoint == "" {
return fnerrors.New("cluster does not have ssh")
}
if sshSvc.Status != "READY" {
return fnerrors.New("expected ssh to be READY, saw %q", sshSvc.Status)
}
signer, err := ssh.ParsePrivateKey(cluster.SshPrivateKey)
if err != nil {
return err
}
peerConn, err := api.DialEndpoint(ctx, sshSvc.Endpoint)
if err != nil {
return err
}
config := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
}
c, chans, reqs, err := ssh.NewClientConn(peerConn, "internal", config)
if err != nil {
return err
}
client := ssh.NewClient(c, chans, reqs)
defer client.Close()
return callback(ctx, client)
}
func inlineSsh(ctx context.Context, cluster *api.KubernetesCluster, sshAgent bool, args []string) error {
stdin, err := c.ConsoleFromFile(os.Stdin)
if err != nil {
return err
}
if !isatty.IsTerminal(stdin.Fd()) {
return fnerrors.New("stdin is not a tty")
}
return withSsh(ctx, cluster, func(ctx context.Context, client *ssh.Client) error {
session, err := client.NewSession()
if err != nil {
return err
}
if sshAgent {
if authSock := os.Getenv("SSH_AUTH_SOCK"); authSock != "" {
if err := agent.ForwardToRemote(client, authSock); err != nil {
return err
}
if err := agent.RequestAgentForwarding(session); err != nil {
return err
}
} else {
fmt.Fprintf(console.Warnings(ctx), "ssh-agent forwarding requested, without a SSH_AUTH_SOCK\n")
}
}
session.Stdin = stdin
session.Stdout = os.Stdout
session.Stderr = os.Stderr
defer session.Close()
done := con.EnterInputMode(ctx)
defer done()
if err := stdin.SetRaw(); err != nil {
return err
}
defer stdin.Reset()
w, h, err := term.GetSize(int(stdin.Fd()))
if err != nil {
return err
}
go listenForResize(ctx, stdin, session)
if err := session.RequestPty("xterm", h, w, nil); err != nil {
return err
}
if len(args) > 0 {
command := strings.Join(args, " ")
if err := session.Run(command); err != nil {
return err
}
return nil
} else {
if err := session.Shell(); err != nil {
return err
}
g := executor.New(ctx, "ssh")
cancel := g.GoCancelable(func(ctx context.Context) error {
return api.StartRefreshing(ctx, api.Methods, cluster.ClusterId, func(err error) error {
fmt.Fprintf(os.Stderr, "failed to refresh cluster: %v\n", err)
return nil
})
})
g.Go(func(ctx context.Context) error {
defer cancel()
return session.Wait()
})
return g.Wait()
}
})
}
func listenForResize(ctx context.Context, stdin c.Console, session *ssh.Session) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGWINCH)
defer func() {
signal.Stop(sig)
}()
for {
select {
case <-ctx.Done():
return
case <-sig:
}
w, h, err := term.GetSize(int(stdin.Fd()))
if err == nil {
session.WindowChange(h, w)
}
}
}