-
Notifications
You must be signed in to change notification settings - Fork 19
/
pty.go
210 lines (181 loc) · 5.23 KB
/
pty.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
package sshego
/*
See blog: https://blog.gopheracademy.com/go-and-ssh/
Code from https://github.com/jpillora/go-and-ssh
licensed under:
#### MIT License
Copyright (c) 2014 Jaime Pillora <dev@jpillora.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// A small SSH daemon providing bash sessions
//
// Server:
// cd my/new/dir/
// #generate server keypair
// ssh-keygen -t rsa
// go get -v .
// go run sshd.go
//
// Client:
// ssh foo@localhost -p 2200 #pass=bar
import (
"context"
"encoding/binary"
"fmt"
"io"
"log"
"os/exec"
"sync"
"syscall"
"unsafe"
"github.com/glycerine/sshego/xendor/github.com/glycerine/xcryptossh"
"github.com/kr/pty"
)
type ConnectionAlert struct {
PortOne chan ssh.Channel
ShutDown chan struct{}
}
func (cfg *SshegoConfig) handleChannels(ctx context.Context, chans <-chan ssh.NewChannel, sshconn ssh.Conn, ca *ConnectionAlert) {
// Service the incoming Channel channel in go routine
var shut chan struct{}
if ca != nil {
shut = ca.ShutDown
}
for {
select {
case newChannel, stillOpen := <-chans:
if !stillOpen {
return
}
go cfg.handleChannel(ctx, newChannel, sshconn, ca)
case <-cfg.Esshd.Halt.ReqStop.Chan:
return
case <-shut:
return
case <-ctx.Done():
return
}
}
}
func (cfg *SshegoConfig) handleChannel(ctx context.Context, newChannel ssh.NewChannel, sshconn ssh.Conn, ca *ConnectionAlert) {
// Since we're handling a shell, we expect a
// channel type of "session". The spec also describes
// "x11", "direct-tcpip" and "forwarded-tcpip"
// channel types.
if newChannel == nil {
// can happen on shutdown
return
}
t := newChannel.ChannelType()
if t == "direct-tcpip" {
handleDirectTcp(ctx, newChannel, ca)
}
if t != "session" {
if len(cfg.CustomChannelHandlers) > 0 {
cb, ok := cfg.CustomChannelHandlers[t]
if ok {
go cb(newChannel, sshconn, ca)
return
}
}
newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t))
return
}
// t == "session", request to open a shell
// At this point, we have the opportunity to reject the client's
// request for another logical connection
connection, requests, err := newChannel.Accept()
if err != nil {
log.Printf("Could not accept channel (%s)", err)
return
}
// Fire up bash for this session
bash := exec.Command("bash")
// Prepare teardown function
close := func() {
connection.Close()
_, err := bash.Process.Wait()
if err != nil {
log.Printf("Failed to exit bash (%s)", err)
}
log.Printf("Session closed")
}
// Allocate a terminal for this channel
log.Print("Successful login, creating pty...")
bashf, err := pty.Start(bash)
if err != nil {
log.Printf("Could not start pty (%s)", err)
close()
return
}
//pipe session to bash and visa-versa
var once sync.Once
go func() {
io.Copy(connection, bashf)
once.Do(close)
}()
go func() {
io.Copy(bashf, connection)
once.Do(close)
}()
// Sessions have out-of-band requests such as "shell", "pty-req" and "env"
go func() {
for req := range requests {
switch req.Type {
case "shell":
// We only accept the default shell
// (i.e. no command in the Payload)
if len(req.Payload) == 0 {
req.Reply(true, nil)
}
case "pty-req":
termLen := req.Payload[3]
w, h := parseDims(req.Payload[termLen+4:])
SetWinsize(bashf.Fd(), w, h)
// Responding true (OK) here will let the client
// know we have a pty ready for input
req.Reply(true, nil)
case "window-change":
w, h := parseDims(req.Payload)
SetWinsize(bashf.Fd(), w, h)
}
}
}()
}
// =======================
// parseDims extracts terminal dimensions (width x height) from the provided buffer.
func parseDims(b []byte) (uint32, uint32) {
w := binary.BigEndian.Uint32(b)
h := binary.BigEndian.Uint32(b[4:])
return w, h
}
// ======================
// Winsize stores the Height and Width of a terminal.
type Winsize struct {
Height uint16
Width uint16
x uint16 // unused
y uint16 // unused
}
// SetWinsize sets the size of the given pty.
func SetWinsize(fd uintptr, w, h uint32) {
ws := &Winsize{Width: uint16(w), Height: uint16(h)}
syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
}
// note in the original:
// Borrowed from https://github.com/creack/termios/blob/master/win/win.go