-
Notifications
You must be signed in to change notification settings - Fork 30
/
serverconn.go
316 lines (292 loc) · 7.21 KB
/
serverconn.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
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// TODO: High-level file comment.
package main
import (
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/user"
"runtime"
"sync"
"github.com/google/shlex"
"github.com/matir/sshdog/pty"
"golang.org/x/crypto/ssh"
)
// Handling for a single incoming connection
type ServerConn struct {
*Server
*ssh.ServerConn
pty *pty.Pty
reqs <-chan *ssh.Request
chans <-chan ssh.NewChannel
environ []string
exitStatus uint32
}
func NewServerConn(conn net.Conn, s *Server) (*ServerConn, error) {
sConn, chans, reqs, err := ssh.NewServerConn(conn, &s.ServerConfig)
if err != nil {
return nil, err
}
return &ServerConn{
Server: s,
ServerConn: sConn,
reqs: reqs,
chans: chans,
environ: os.Environ(),
}, nil
}
func (conn *ServerConn) ServiceGlobalRequests() {
for r := range conn.reqs {
dbg.Debug("Received request %s plus %d bytes.", r.Type, len(r.Payload))
if r.WantReply {
r.Reply(true, []byte{})
}
}
}
// Handle a single established connection
func (conn *ServerConn) HandleConn() {
defer func() {
dbg.Debug("Closing connection to: %s", conn.RemoteAddr())
conn.Close()
}()
go conn.ServiceGlobalRequests()
wg := &sync.WaitGroup{}
for newChan := range conn.chans {
dbg.Debug("Incoming channel request: %s", newChan.ChannelType())
switch newChan.ChannelType() {
case "session":
wg.Add(1)
go conn.HandleSessionChannel(wg, newChan)
case "direct-tcpip":
wg.Add(1)
go conn.HandleTCPIPChannel(wg, newChan)
default:
dbg.Debug("Unable to handle channel request, rejecting.")
newChan.Reject(ssh.Prohibited, "Prohibited")
}
}
wg.Wait()
}
type PTYRequest struct {
Term string
Width uint32
Height uint32
WidthPx uint32
HeightPx uint32
Modes string
}
type EnvRequest struct {
Name string
Value string
}
type ExecRequest struct {
Cmd string
}
func defaultShell() []string {
switch runtime.GOOS {
case "windows":
return []string{
"C:\\windows\\system32\\cmd.exe",
"/Q",
}
default:
return []string{"/bin/sh"}
}
}
func commandWithShell(command string) []string {
switch runtime.GOOS {
case "windows":
return []string{
"C:\\windows\\system32\\cmd.exe",
"/C",
command,
}
default:
return []string{
"/bin/sh",
"-c",
command,
}
}
}
func (conn *ServerConn) HandleSessionChannel(wg *sync.WaitGroup, newChan ssh.NewChannel) {
// TODO: refactor this, too long
defer wg.Done()
ch, reqs, err := newChan.Accept()
if err != nil {
dbg.Debug("Unable to accept newChan: %v", err)
return
}
defer func() {
b := ssh.Marshal(struct{ ExitStatus uint32 }{conn.exitStatus})
ch.SendRequest("exit-status", false, b)
dbg.Debug("Closing session channel.")
ch.Close()
}()
var success bool
for req := range reqs {
switch req.Type {
case "pty-req":
ptyreq := &PTYRequest{}
success = true
if err := ssh.Unmarshal(req.Payload, ptyreq); err != nil {
dbg.Debug("Error unmarshaling pty-req: %v", err)
success = false
}
conn.pty, err = pty.OpenPty()
if conn.pty != nil {
conn.pty.Resize(uint16(ptyreq.Height), uint16(ptyreq.Width), uint16(ptyreq.WidthPx), uint16(ptyreq.HeightPx))
os.Setenv("TERM", ptyreq.Term)
// TODO: set pty modes
}
if err != nil {
dbg.Debug("Failed allocating pty: %v", err)
success = false
}
if req.WantReply {
req.Reply(success, []byte{})
}
case "env":
envreq := &EnvRequest{}
if err := ssh.Unmarshal(req.Payload, envreq); err != nil {
dbg.Debug("Error unmarshaling env: %v", err)
success = false
} else {
dbg.Debug("env: %s=%s", envreq.Name, envreq.Value)
conn.environ = append(conn.environ, fmt.Sprintf("%s=%s", envreq.Name, envreq.Value))
success = true
}
if req.WantReply {
req.Reply(success, []byte{})
}
case "shell":
// TODO: get the user's shell
conn.ExecuteForChannel(defaultShell(), ch)
if req.WantReply {
req.Reply(true, []byte{})
}
return
case "exec":
execReq := &ExecRequest{}
if err := ssh.Unmarshal(req.Payload, execReq); err != nil {
dbg.Debug("Error unmarshaling exec: %v", err)
success = false
} else {
if cmd, err := shlex.Split(execReq.Cmd); err == nil {
dbg.Debug("Command: %v", cmd)
if req.WantReply {
req.Reply(true, []byte{})
}
if cmd[0] == "scp" {
if err := conn.SCPHandler(cmd, ch); err != nil {
dbg.Debug("scp failure: %v", err)
conn.exitStatus = 1
}
} else {
conn.exitStatus = conn.ExecuteForChannel(commandWithShell(execReq.Cmd), ch)
}
} else {
dbg.Debug("Error splitting cmd: %v", err)
if req.WantReply {
req.Reply(false, []byte{})
}
}
}
return
default:
dbg.Debug("Unknown session request: %s", req.Type)
if req.WantReply {
req.Reply(false, []byte{})
}
}
}
}
// Execute a process for the channel.
func (conn *ServerConn) ExecuteForChannel(shellCmd []string, ch ssh.Channel) uint32 {
dbg.Debug("Executing %v", shellCmd)
var exerr *exec.ExitError
proc := exec.Command(shellCmd[0], shellCmd[1:]...)
proc.Env = conn.environ
if userInfo, err := user.Current(); err == nil {
proc.Dir = userInfo.HomeDir
}
if conn.pty == nil {
stdin, _ := proc.StdinPipe()
go func() {
defer stdin.Close()
io.Copy(stdin, ch)
}()
proc.Stdout = ch
proc.Stderr = ch.Stderr()
} else {
conn.pty.AttachPty(proc)
conn.pty.AttachIO(ch, ch)
}
err := proc.Run()
if errors.As(err, &exerr) {
dbg.Debug("Finished execution with error: %v", err)
return uint32(exerr.ExitCode())
} else {
dbg.Debug("Finished execution.")
return 0
}
}
// Message for port forwarding
type tcpipMessage struct {
Host string
Port uint32
SourceIP string
SourcePort uint32
}
func (conn *ServerConn) HandleTCPIPChannel(wg *sync.WaitGroup, newChan ssh.NewChannel) {
defer wg.Done()
var msg tcpipMessage
if err := ssh.Unmarshal(newChan.ExtraData(), &msg); err != nil {
dbg.Debug("Unable to setup forwarding: %v", err)
newChan.Reject(ssh.ResourceShortage, "Error parsing message.")
return
}
dbg.Debug("Forwarding request: %v", msg)
outbound, err := net.Dial("tcp", fmt.Sprintf("%s:%d", msg.Host, msg.Port))
if err != nil {
dbg.Debug("Unable to dial forward: %v", err)
newChan.Reject(ssh.ConnectionFailed, err.Error())
return
}
defer outbound.Close()
ch, reqs, err := newChan.Accept()
if err != nil {
dbg.Debug("Unable to accept chan: %v", err)
return
}
defer ch.Close()
go func() {
for req := range reqs {
switch req.Type {
default:
dbg.Debug("Unknown direct-tcpip request: %s", req.Type)
if req.WantReply {
req.Reply(false, []byte{})
}
}
}
}()
go io.Copy(ch, outbound)
io.Copy(outbound, ch)
dbg.Debug("Closing forwarding request: %v", msg)
}