forked from gliderlabs/sshfront
/
handlers.go
302 lines (264 loc) · 6.49 KB
/
handlers.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
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"github.com/flynn/go-shlex"
"github.com/kr/pty"
"golang.org/x/crypto/ssh"
)
type exitStatusMsg struct {
Status uint32
}
func exitStatus(err error) (exitStatusMsg, error) {
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// There is no platform independent way to retrieve
// the exit code, but the following will work on Unix
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
return exitStatusMsg{uint32(status.ExitStatus())}, nil
}
}
return exitStatusMsg{0}, err
}
return exitStatusMsg{0}, nil
}
func handlerCmd(handler string, appendArgs ...string) (*exec.Cmd, error) {
handlerSplit, err := shlex.Split(handler)
if err != nil {
return nil, err
}
var args []string
executable := handlerSplit[0]
if len(handlerSplit) > 1 {
args = handlerSplit[1:]
}
path, err := exec.LookPath(executable)
if err == nil {
executable = path
}
execPath, err := filepath.Abs(executable)
if err != nil {
return nil, fmt.Errorf("unable to locate handler: %s", executable)
}
return exec.Command(execPath, append(args, appendArgs...)...), nil
}
func handleAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if *authHook == "" {
// allow all
return &ssh.Permissions{
Extensions: map[string]string{
"user": conn.User(),
},
}, nil
}
keydata := string(bytes.TrimSpace(ssh.MarshalAuthorizedKey(key)))
cmd, err := handlerCmd(*authHook, conn.User(), keydata)
if err != nil {
return nil, err
}
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
status, err := exitStatus(cmd.Run())
if err != nil {
return nil, err
}
if status.Status == 0 {
return &ssh.Permissions{
Extensions: map[string]string{
"environ": strings.Trim(output.String(), "\n"),
"user": conn.User(),
},
}, nil
}
debug("authentication hook status:", status.Status)
return nil, fmt.Errorf("authentication failed")
}
func handleChannel(conn *ssh.ServerConn, newChan ssh.NewChannel) {
ch, reqs, err := newChan.Accept()
if err != nil {
log.Println("newChan.Accept failed:", err)
return
}
// Setup stdout/stderr
var stdout, stderr io.Writer
if *debugMode {
stdout = io.MultiWriter(ch, os.Stdout)
stderr = io.MultiWriter(ch.Stderr(), os.Stdout)
} else {
stdout = ch
stderr = ch.Stderr()
}
handler := sshHandler{
channel: ch,
stdout: stdout,
stderr: stderr,
}
// Load default environment
if *useEnv {
handler.Env = os.Environ()
}
if conn.Permissions != nil {
// Using Permissions.Extensions as a way to get state from PublicKeyCallback
if conn.Permissions.Extensions["environ"] != "" {
handler.Env = append(handler.Env, strings.Split(conn.Permissions.Extensions["environ"], "\n")...)
}
handler.Env = append(handler.Env, "USER="+conn.Permissions.Extensions["user"])
}
for req := range reqs {
go handler.Request(req)
}
}
// sshHandler is a stateful handler for requests within an SSH channel
type sshHandler struct {
sync.Mutex
Env []string
channel ssh.Channel
stdout io.Writer
stderr io.Writer
ptyShell *os.File
}
func (h *sshHandler) assert(at string, err error) bool {
if err != nil {
log.Printf("%s failed: %s", at, err)
h.stderr.Write([]byte("Internal error.\n"))
return true
}
return false
}
// Exit sends an exit-status request to the channel based on the err.
func (h *sshHandler) Exit(err error) error {
defer h.channel.Close()
status, err := exitStatus(err)
if !h.assert("exit", err) {
_, err := h.channel.SendRequest("exit-status", false, ssh.Marshal(&status))
h.assert("status", err)
return err
}
return err
}
type EnvVar struct {
Name, Value string
}
func (h *sshHandler) Request(req *ssh.Request) {
switch req.Type {
case "exec":
h.handleExec(req)
case "env":
h.handleEnv(req)
case "pty-req":
h.handlePty(req)
case "window-change":
h.handleWinch(req)
default:
if req.WantReply {
req.Reply(true, nil)
}
}
}
func (h *sshHandler) handleEnv(req *ssh.Request) {
var pair EnvVar
ssh.Unmarshal(req.Payload, &pair)
envvar := fmt.Sprintf("%s=%s", pair.Name, pair.Value)
h.Env = append(h.Env, envvar)
req.Reply(true, nil)
}
func (h *sshHandler) handleExec(req *ssh.Request) {
h.Lock()
defer h.Unlock()
var payload = struct{ Value string }{}
ssh.Unmarshal(req.Payload, &payload)
cmdargs, err := shlex.Split(payload.Value)
if err != nil {
debug("failed exec split:", err)
h.channel.Close()
return
}
cmd, err := handlerCmd(flag.Arg(0), cmdargs...)
if err != nil {
debug("failed handler init:", err)
h.channel.Close()
return
}
cmd.Env = append(h.Env, "SSH_ORIGINAL_COMMAND="+strings.Join(cmdargs, " "))
cmd.Stdout = h.stdout
cmd.Stderr = h.stderr
// cmd.Wait closes the stdin when it's done, so we need to proxy it through a pipe
stdinPipe, err := cmd.StdinPipe()
if h.assert("exec cmd.StdinPipe", err) {
h.channel.Close()
return
}
go io.Copy(stdinPipe, h.channel)
if req.WantReply {
req.Reply(true, nil)
}
// We run inline to prevent concurrent exec requests for the channel as the lock is held.
h.Exit(cmd.Run())
}
func (h *sshHandler) handlePty(req *ssh.Request) {
h.Lock()
defer h.Unlock()
if h.ptyShell != nil {
// Only allow one pty per channel
req.Reply(false, nil)
return
}
width, height, okSize := parsePtyRequest(req.Payload)
cmd, err := handlerCmd(flag.Arg(0))
if err != nil {
debug("failed handler init:", err)
h.channel.Close()
return
}
cmd.Env = h.Env
// attachShell does cmd.Start() so we need to do cmd.Wait() later
ptyShell, _, err := attachShell(cmd, h.stdout, h.channel)
if h.assert("pty attachShell", err) {
h.channel.Close()
return
}
h.ptyShell = ptyShell
if okSize {
setWinsize(ptyShell.Fd(), width, height)
}
// Ready to receive input
req.Reply(true, nil)
// We run this concurrently so that the lock is released for window-change events.
go h.Exit(cmd.Wait())
}
func (h *sshHandler) handleWinch(req *ssh.Request) {
h.Lock()
defer h.Unlock()
width, height, okSize := parsePtyRequest(req.Payload)
if okSize && h.ptyShell != nil {
setWinsize(h.ptyShell.Fd(), width, height)
}
}
func attachShell(cmd *exec.Cmd, stdout io.Writer, stdin io.Reader) (*os.File, *sync.WaitGroup, error) {
var wg sync.WaitGroup
wg.Add(2)
// Note that pty merges stdout and stderr.
cmdPty, err := pty.Start(cmd)
if err != nil {
return nil, nil, err
}
go func() {
io.Copy(stdout, cmdPty)
wg.Done()
}()
go func() {
io.Copy(cmdPty, stdin)
wg.Done()
}()
return cmdPty, &wg, nil
}