-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh.go
324 lines (272 loc) · 7.06 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
package main
import (
"bytes"
"fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"io"
"log"
"net"
"os"
"path"
"strings"
"time"
)
// Command to run on each remote host
type SSHCommand struct {
Command string
Sudo bool
Pty bool
Timeout time.Duration
Files []string
ForwardAgent bool
}
// A single SSH connection to a remote host
type SSHSession struct {
Host string
Config *ssh.ClientConfig
Remote *RemoteIO
connection *ssh.Client
auth *Auth
}
// Creates an SSHCommand
func NewSSHCommand(cmd string, sudo, pty, forwardAgent bool, timeout time.Duration, files []string) *SSHCommand {
return &SSHCommand{
Command: cmd,
Sudo: sudo,
Pty: pty,
Timeout: timeout,
Files: files,
ForwardAgent: forwardAgent,
}
}
// Creates an (unconnected) SSH client
func NewSSHSession(host, user string, auth *Auth, remote *RemoteIO) *SSHSession {
return &SSHSession{
Host: host,
Remote: remote,
auth: auth,
Config: &ssh.ClientConfig{
User: user,
Auth: auth.getAuthMethods(),
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
},
}
}
// Initiates the connection for this client
func (sesh *SSHSession) Connect(port int) error {
log.Printf("Starting connection to %s", sesh.Host)
connection, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", sesh.Host, port), sesh.Config)
if err != nil {
return err
}
sesh.connection = connection
return nil
}
// Closes this ssh session
func (sesh *SSHSession) Close() {
sesh.connection.Close()
sesh.connection = nil
}
// Runs the specified SSHCommand
func (sesh *SSHSession) Run(cmd *SSHCommand) error {
if len(cmd.Files) > 0 {
tmpdir, err := sesh.mktemp()
if err != nil {
return err
}
defer sesh.deltemp(tmpdir)
if err := sesh.sendFiles(tmpdir, cmd.Files); err != nil {
return err
}
return sesh.runCommand(cmd, tmpdir)
} else {
return sesh.runCommand(cmd, "")
}
}
// Runs the actual shell command from the specified directory
func (sesh *SSHSession) runCommand(cmd *SSHCommand, dir string) error {
if cmd.ForwardAgent {
if err := sesh.auth.forwardAgent(sesh.connection); err != nil {
return err
}
}
log.Printf("Initiating session on %s", sesh.Host)
session, err := sesh.connection.NewSession()
if err != nil {
return err
}
defer session.Close()
if cmd.ForwardAgent {
if err := agent.RequestAgentForwarding(session); err != nil {
return err
}
}
if cmd.Sudo || cmd.Pty {
tmodes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
log.Printf("Requesting pty on %s", sesh.Host)
if err := session.RequestPty("xterm", 80, 25, tmodes); err != nil {
return err
}
}
stdout, err := session.StdoutPipe()
if err != nil {
return err
}
stderr, err := session.StderrPipe()
if err != nil {
return err
}
timeout := time.AfterFunc(cmd.Timeout, func() {
session.Close()
})
shcmd := cmd.Command
if dir != "" {
shcmd = fmt.Sprintf("cd %s; %s", dir, shcmd)
}
var cmdErr error
if cmd.Sudo {
stdin, err := session.StdinPipe()
if err != nil {
return err
}
go sesh.writePass(stdin, stdout)
go io.Copy(&stderrWriter{sesh.Remote}, stderr)
log.Printf("Invoking cmd on %s", sesh.Host)
cmdErr = session.Run(fmt.Sprintf("/usr/bin/sudo /bin/bash -c '%s'", shcmd))
} else {
go io.Copy(&stdoutWriter{sesh.Remote}, stdout)
go io.Copy(&stderrWriter{sesh.Remote}, stderr)
log.Printf("Invoking cmd on %s", sesh.Host)
cmdErr = session.Run(shcmd)
}
timeout.Stop()
if cmdErr == nil {
// Exited normally.
log.Printf("Cmd on %s terminated normally", sesh.Host)
sesh.Remote.Exit(0)
return nil
} else if exitError, ok := cmdErr.(*ssh.ExitError); ok {
// Exited with error status.
log.Printf("Cmd on %s terminated with code %d", exitError.ExitStatus())
sesh.Remote.Exit(exitError.ExitStatus())
return nil
} else {
// Abnormally exited.
log.Printf("Cmd on %s terminated abnormally: %s", sesh.Host, cmdErr.Error())
return cmdErr
}
}
// Waits for sudo password prompt, then writes the password, while forwarding
// all stdout to the specified io.Reader.
func (sesh *SSHSession) writePass(stdin io.WriteCloser, stdout io.Reader) {
var buf bytes.Buffer
sect := make([]byte, 32)
for {
n, err := stdout.Read(sect)
if err != nil {
log.Printf("Read error while waiting for password on %s: %s", sesh.Host, err.Error())
return
}
buf.Write(sect[:n])
sesh.Remote.Stdout(sect[:n])
if bytes.Contains(buf.Bytes(), []byte("[sudo] password for ")) {
log.Printf("Responding to password prompt on %s", sesh.Host)
pw, err := sesh.auth.getPassword()
if err != nil {
// Welp...
break
}
stdin.Write([]byte(pw))
stdin.Write([]byte{'\r'})
break
}
if buf.Len() > 256 {
// Should be early, but sudo might print out warning messages, e.g. if DNS resolution
// is funky on the box. But if it goes too far out, then don't bother.
log.Println("No sudo prompt found in first 256 bytes, skipping.")
break
}
}
stdin.Close()
io.Copy(&stdoutWriter{sesh.Remote}, stdout)
}
// Creates a temporary directory on the remote host.
func (sesh *SSHSession) mktemp() (string, error) {
log.Printf("Creating temporary directory on %s", sesh.Host)
session, err := sesh.connection.NewSession()
if err != nil {
return "", err
}
defer session.Close()
result, err := session.CombinedOutput("mktemp -d")
if err != nil {
return "", err
}
return strings.TrimRight(string(result), "\r\n"), nil
}
// Deletes a directory from the remote host.
func (sesh *SSHSession) deltemp(dir string) error {
log.Printf("Removing temporary directory on %s", sesh.Host)
session, err := sesh.connection.NewSession()
if err != nil {
return err
}
defer session.Close()
return session.Run("rm -rf " + dir)
}
// Sends the specified files to the specified directory on the remote host
// via scp, preserving file modes.
func (sesh *SSHSession) sendFiles(dir string, files []string) error {
log.Printf("Preparing to send files to %s", sesh.Host)
session, err := sesh.connection.NewSession()
if err != nil {
return err
}
defer session.Close()
stdin, err := session.StdinPipe()
if err != nil {
return err
}
result := make(chan error, 1)
go func() {
defer stdin.Close()
for _, file := range files {
log.Printf("Sending %s to %s", file, sesh.Host)
f, err := os.Open(file)
if err != nil {
log.Printf("Failed to open %s: %s", file, err.Error())
result <- err
return
}
info, err := f.Stat()
if err != nil {
f.Close()
log.Printf("Failed to stat %s: %s", file, err.Error())
result <- err
return
}
fmt.Fprintf(stdin, "C%04o %d %s\n", info.Mode().Perm(), info.Size(), path.Base(file))
io.Copy(stdin, f)
fmt.Fprintf(stdin, "\x00")
f.Close()
}
result <- nil
}()
out, err := session.CombinedOutput(fmt.Sprintf("/usr/bin/scp -tr %s", dir))
if err != nil {
log.Printf("File copy failed on %s [%s] remote: %s", sesh.Host, err.Error(), out)
}
sendErr := <-result
if err == nil {
err = sendErr
}
close(result)
return err
}