-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
236 lines (214 loc) · 5.9 KB
/
main.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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"fmt"
"github.com/creack/pty"
"golang.org/x/crypto/ssh"
"io"
"log"
"net"
"os/exec"
"strings"
"sync"
"syscall"
"unsafe"
)
func generateSigner() (ssh.Signer, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
return ssh.NewSignerFromKey(key)
}
func fingerprint(k ssh.PublicKey) string {
bytes := sha256.Sum256(k.Marshal())
b64 := base64.StdEncoding.EncodeToString(bytes[:])
if strings.HasSuffix(b64, "=") {
b64 = strings.TrimSuffix(b64, "=") + "."
}
return "SHA256:" + b64
}
func main() {
config := &ssh.ServerConfig{
//Define a function to run when a client attempts a password login
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
// Should use constant-time compare (or better, salt+hash) in a production setting.
if c.User() == "foo" && string(pass) == "bar" {
return nil, nil
}
return nil, fmt.Errorf("password rejected for %q", c.User())
},
// You may also explicitly allow anonymous client authentication, though anon bash
// sessions may not be a wise idea
// NoClientAuth: true,
ServerVersion: "SSH-2.0-GO-SERVER",
BannerCallback: func(conn ssh.ConnMetadata) string {
fmt.Printf("session:%s remote:%s local:%s user:%s\n", conn.SessionID(), conn.RemoteAddr(), conn.LocalAddr(), conn.User())
return "hello func\n"
},
}
pri, err := generateSigner()
log.Printf("%#v", pri.PublicKey())
if err != nil {
log.Println(err)
}
config.AddHostKey(pri)
log.Printf("RSA key fingerprint is %s", fingerprint(pri.PublicKey()))
listener, err := net.Listen("tcp", "127.0.0.1:2222")
if err != nil {
log.Fatalf("Failed to listen on 2200 (%s)", err)
}
// Accept all connections
for {
tcpConn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept incoming connection (%s)", err)
continue
}
// Before use, a handshake must be performed on the incoming net.Conn.
sshConn, chans, reqs, err := ssh.NewServerConn(tcpConn, config)
if err != nil {
log.Printf("Failed to handshake (%s)", err)
continue
}
log.Printf("New SSH connection from %s (%s)", sshConn.RemoteAddr(), sshConn.ClientVersion())
handle(tcpConn)
// Discard all global out-of-band Requests
go ssh.DiscardRequests(reqs)
// Accept all channels
go handleChannels(chans)
}
}
func handleChannels(chans <-chan ssh.NewChannel) {
// Service the incoming Channel channel in go routine
for newChannel := range chans {
go handleChannel(newChannel)
}
}
func handleChannel(newChannel ssh.NewChannel) {
// Since we're handling a shell, we expect a
// channel type of "session". The also describes
// "x11", "direct-tcpip" and "forwarded-tcpip"
// channel types.
if t := newChannel.ChannelType(); t != "session" {
// 仅处理 session 类型的 channel,其他的 channel 暂时不处理
newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t))
return
}
// 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("/bin/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("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)))
}
func handle(upConn net.Conn) {
defer upConn.Close()
log.Printf("accepted: %s", upConn.RemoteAddr())
downConn, err := net.Dial("tcp", "10.127.253.187:22")
if err != nil {
log.Printf("unable to connect to %s: %s", "10.127.253.187:22", err)
return
}
defer downConn.Close()
if err := Pipe(upConn, downConn); err != nil {
log.Printf("pipe failed: %s", err)
} else {
log.Printf("disconnected: %s", upConn.RemoteAddr())
}
}
func Pipe(a, b net.Conn) error {
done := make(chan error, 1)
cp := func(r, w net.Conn) {
n, err := io.Copy(r, w)
log.Printf("copied %d bytes from %s to %s", n, r.RemoteAddr(), w.RemoteAddr())
done <- err
}
go cp(a, b)
go cp(b, a)
err1 := <-done
err2 := <-done
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return nil
}