-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathshell.go
330 lines (288 loc) · 7.96 KB
/
shell.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
package sshutil
import (
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"golang.org/x/term"
"github.com/smallstep/cli-utils/step"
)
// ProxyCommand replaces %%, %h, %p, and %r in the given command.
//
// %% A literal `%`.
// %h The remote hostname.
// %p The remote port.
// %r The remote username.
func ProxyCommand(cmd, user, host, port string) string {
cmd = strings.ReplaceAll(cmd, "%%", "%")
cmd = strings.ReplaceAll(cmd, "%h", host)
cmd = strings.ReplaceAll(cmd, "%p", port)
return strings.ReplaceAll(cmd, "%r", user)
}
// ShellOption is the type used to add new options to the shell.
type ShellOption func(s *Shell) error
// WithAuthMethod adds a new ssh.AuthMethod to the shell.
func WithAuthMethod(am ssh.AuthMethod) ShellOption {
return func(s *Shell) error {
s.authMethods = append(s.authMethods, am)
return nil
}
}
// WithSigner adds the given signer as an ssh.AuthMethod.
func WithSigner(signer ssh.Signer) ShellOption {
return func(s *Shell) error {
s.authMethods = append(s.authMethods, ssh.PublicKeys(signer))
return nil
}
}
// WithCertificate adds a signer with the given certificate as an
// ssh.AuthMethod.
func WithCertificate(cert *ssh.Certificate, priv interface{}) ShellOption {
return func(s *Shell) error {
signer, err := NewCertSigner(cert, priv)
if err != nil {
return err
}
s.authMethods = append(s.authMethods, ssh.PublicKeys(signer))
return nil
}
}
// withDefaultAuthMethod adds the ssh.Agent as an ssh.AuthMethod.
func withDefaultAuthMethod() ShellOption {
return func(s *Shell) error {
agent, err := DialAgent()
if err != nil {
return err
}
s.authMethods = append(s.authMethods, agent.AuthMethod())
return nil
}
}
// withDefaultDialer adds a direct connection dialer.
func withDefaultDialer(user, address string) ShellOption {
return func(s *Shell) error {
s.dialer = func(callback ssh.HostKeyCallback) (*ssh.Client, error) {
client, err := ssh.Dial("tcp", address, &ssh.ClientConfig{
User: user,
Auth: s.authMethods,
HostKeyCallback: callback,
})
if err != nil {
return nil, errors.Wrapf(err, "error connecting %s", address)
}
return client, nil
}
return nil
}
}
func formatAddress(address string) string {
if _, _, err := net.SplitHostPort(address); err != nil {
address += ":22"
}
return address
}
// Shell implements a remote shell to an SSH server using x/crypto/ssh
type Shell struct {
user string
address string
authMethods []ssh.AuthMethod
client *ssh.Client
dialer func(callback ssh.HostKeyCallback) (*ssh.Client, error)
}
// NewShell initializes a new shell to the given address.
func NewShell(user, address string, opts ...ShellOption) (*Shell, error) {
address = formatAddress(address)
// Use known_host as HostKeyCallback
knownHosts, err := knownhosts.New(filepath.Join(step.Home(), ".ssh", "known_hosts"))
if err != nil {
return nil, errors.Wrap(err, "error reading known_hosts")
}
shell := &Shell{
user: user,
address: address,
}
if err := shell.apply(opts); err != nil {
return nil, err
}
if len(shell.authMethods) == 0 {
if err := withDefaultAuthMethod()(shell); err != nil {
return nil, err
}
}
if shell.dialer == nil {
if err := withDefaultDialer(user, address)(shell); err != nil {
return nil, err
}
}
if shell.client, err = shell.dialer(knownHosts); err != nil {
return nil, err
}
return shell, nil
}
func (s *Shell) apply(opts []ShellOption) error {
for _, fn := range opts {
if err := fn(s); err != nil {
return err
}
}
return nil
}
// Close finalizes the connection.
func (s *Shell) Close() error {
return s.client.Close()
}
// Run runs cmd on the remote host.
func (s *Shell) Run(cmd string) error {
// Create a session
session, err := s.client.NewSession()
if err != nil {
return errors.Wrap(err, "error creating a session")
}
defer session.Close()
return session.Run(cmd)
}
// RemoteShell starts a login shell on the remote host.
func (s *Shell) RemoteShell() error {
// Create a session
session, err := s.client.NewSession()
if err != nil {
return errors.Wrap(err, "error creating a session")
}
defer session.Close()
var fallback bool
if fd := int(os.Stdin.Fd()); term.IsTerminal(fd) {
// Put terminal in raw mode
if originalState, err := term.MakeRaw(fd); err != nil {
fallback = true
} else {
defer term.Restore(fd, originalState)
// Get terminal size
w, h, err := term.GetSize(fd)
if err != nil {
w, h = 80, 40
}
// Request pseudo terminal
if err := requestPty(session, h, w, ssh.TerminalModes{
ssh.ECHO: 1, // enable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}); err != nil {
return err
}
}
} else {
fallback = true
}
if fallback {
if err := requestPty(session, 40, 80, ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}); err != nil {
return errors.Wrap(err, "error getting pseudo terminal")
}
}
stdin, err := session.StdinPipe()
if err != nil {
return errors.Wrap(err, "cannot setup stdin for session")
}
go io.Copy(stdin, os.Stdin)
stdout, err := session.StdoutPipe()
if err != nil {
return errors.Wrap(err, "cannot setup stdout for session")
}
go io.Copy(os.Stdout, stdout)
stderr, err := session.StderrPipe()
if err != nil {
return errors.Wrap(err, "cannot setup stderr for session")
}
go io.Copy(os.Stderr, stderr)
// Start remote shell
if err := session.Shell(); err != nil {
return errors.Wrap(err, "error starting remote shell")
}
return session.Wait()
}
// LocalForward creates a local listener in the bindAddress forwarding the
// packages to the remote hostAddress.
func (s *Shell) LocalForward(bindNetwork, bindAddress, hostNetwork, hostAddress string) error {
l, err := net.Listen(bindNetwork, bindAddress)
if err != nil {
return errors.Wrapf(err, "error listening on %s", bindAddress)
}
defer l.Close()
remote, err := s.client.Dial(hostNetwork, hostAddress)
if err != nil {
return errors.Wrapf(err, "error dialing %s", hostAddress)
}
defer remote.Close()
for {
local, err := l.Accept()
if err != nil {
return errors.Wrapf(err, "error connecting to %s", bindAddress)
}
handleConn(local, remote)
}
}
// RemoteForward creates a remote listener in the bindAddress and forwards the
// packages to the local hostAddress.
func (s *Shell) RemoteForward(bindNetwork, bindAddress, hostNetwork, hostAddress string) error {
l, err := s.client.Listen(bindNetwork, bindAddress)
if err != nil {
return errors.Wrapf(err, "error listening on %s", bindAddress)
}
defer l.Close()
for {
local, err := net.Dial(hostNetwork, hostAddress)
if err != nil {
return errors.Wrapf(err, "error dialing %s", hostAddress)
}
remote, err := l.Accept()
if err != nil {
return errors.Wrapf(err, "error connection to %s", bindAddress)
}
handleConn(remote, local)
}
}
func requestPty(session *ssh.Session, h, w int, modes ssh.TerminalModes) (err error) {
var terms []string
switch t := os.Getenv("TERM"); t {
case "", "xterm-256color":
terms = append(terms, "xterm-256color", "xterm")
case "xterm":
terms = append(terms, "xterm")
default:
terms = append(terms, t, "xterm-256color", "xterm")
}
for _, t := range terms {
if err = session.RequestPty(t, h, w, modes); err == nil {
return nil
}
}
return errors.Wrap(err, "error getting pseudo terminal")
}
func handleConn(local, remote net.Conn) {
chDone := make(chan bool)
// Start remote -> local data transfer
go func() {
_, err := io.Copy(local, remote)
if err != nil {
log.Println("error while copy remote->local:", err)
}
chDone <- true
}()
// Start local -> remote data transfer
go func() {
_, err := io.Copy(remote, local)
if err != nil {
log.Println(err)
}
chDone <- true
}()
<-chDone
}