forked from antoniomika/sish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle.go
98 lines (90 loc) · 2.64 KB
/
handle.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
package sshmuxer
import (
"fmt"
"log"
"time"
"github.com/antoniomika/sish/utils"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh"
)
// handleRequests handles incoming requests from an SSH connection.
func handleRequests(reqs <-chan *ssh.Request, sshConn *utils.SSHConnection, state *utils.State) {
for req := range reqs {
if viper.GetBool("debug") {
log.Println("Main Request Info", req.Type, req.WantReply, string(req.Payload))
}
handleRequest(req, sshConn, state)
}
}
// handleRequest handles a incoming request from a SSH connection.
func handleRequest(newRequest *ssh.Request, sshConn *utils.SSHConnection, state *utils.State) {
switch req := newRequest.Type; req {
case "tcpip-forward":
go checkSession(newRequest, sshConn, state)
handleRemoteForward(newRequest, sshConn, state)
case "[email protected]":
err := newRequest.Reply(true, nil)
if err != nil {
log.Println("Error replying to socket request:", err)
}
default:
err := newRequest.Reply(false, nil)
if err != nil {
log.Println("Error replying to socket request:", err)
}
}
}
// checkSession will check a session to see that it has a session.
func checkSession(newRequest *ssh.Request, sshConn *utils.SSHConnection, state *utils.State) {
sshConn.SetupLock.Lock()
if sshConn.CleanupHandler {
sshConn.SetupLock.Unlock()
return
}
sshConn.CleanupHandler = true
sshConn.SetupLock.Unlock()
select {
case <-sshConn.Session:
return
case <-time.After(2 * time.Second):
go func() {
for {
select {
case <-sshConn.Messages:
case <-sshConn.Close:
return
}
}
}()
err := sshConn.SSHConn.Wait()
if err != nil {
log.Println("Waited for ssh conn without session:", err)
}
sshConn.CleanUp(state)
return
}
}
// handleChannels handles a SSH connection's channel requests.
func handleChannels(chans <-chan ssh.NewChannel, sshConn *utils.SSHConnection, state *utils.State) {
for newChannel := range chans {
if viper.GetBool("debug") {
log.Println("Main Channel Info", newChannel.ChannelType(), string(newChannel.ExtraData()))
}
go handleChannel(newChannel, sshConn, state)
}
}
// handleChannel handles a SSH connection's channel request.
func handleChannel(newChannel ssh.NewChannel, sshConn *utils.SSHConnection, state *utils.State) {
switch channel := newChannel.ChannelType(); channel {
case "session":
close(sshConn.Session)
handleSession(newChannel, sshConn, state)
case "direct-tcpip":
handleAlias(newChannel, sshConn, state)
default:
err := newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", channel))
if err != nil {
log.Println("Error rejecting socket channel:", err)
}
}
}