-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
remoteforward.go
125 lines (90 loc) · 2.55 KB
/
remoteforward.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
package handlers
import (
"fmt"
"io"
"log"
"net"
"strconv"
"github.com/NHAS/reverse_ssh/internal"
"golang.org/x/crypto/ssh"
)
var currentRemoteForwards = map[internal.RemoteForwardRequest]net.Listener{}
func StopRemoteForward(rf internal.RemoteForwardRequest) error {
if _, ok := currentRemoteForwards[rf]; !ok {
return fmt.Errorf("Unable to find remote forward request")
}
currentRemoteForwards[rf].Close()
delete(currentRemoteForwards, rf)
return nil
}
func StartRemoteForward(user *internal.User, r *ssh.Request, sshConn ssh.Conn) {
var rf internal.RemoteForwardRequest
err := ssh.Unmarshal(r.Payload, &rf)
if err != nil {
r.Reply(false, []byte(fmt.Sprintf("Unable to open remote forward: %s", err.Error())))
return
}
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", rf.BindAddr, rf.BindPort))
if err != nil {
r.Reply(false, []byte(fmt.Sprintf("Unable to open remote forward: %s", err.Error())))
return
}
defer l.Close()
user.SupportedRemoteForwards[rf] = true
//https://datatracker.ietf.org/doc/html/rfc4254
responseData := []byte{}
if rf.BindPort == 0 {
port := uint32(l.Addr().(*net.TCPAddr).Port)
responseData = ssh.Marshal(port)
rf.BindPort = port
}
r.Reply(true, responseData)
log.Println("Started listening on: ", l.Addr())
currentRemoteForwards[rf] = l
for {
proxyCon, err := l.Accept()
if err != nil {
return
}
go handleData(rf, proxyCon, sshConn)
}
}
func handleData(rf internal.RemoteForwardRequest, proxyCon net.Conn, sshConn ssh.Conn) error {
log.Println("Accepted new connection: ", proxyCon.RemoteAddr())
originatorAddress := proxyCon.LocalAddr().String()
var originatorPort uint32
for i := len(originatorAddress) - 1; i > 0; i-- {
if originatorAddress[i] == ':' {
e, err := strconv.Atoi(originatorAddress[i+1:])
if err != nil {
return err
}
originatorPort = uint32(e)
originatorAddress = originatorAddress[:i]
break
}
}
drtMsg := internal.ChannelOpenDirectMsg{
Raddr: rf.BindAddr,
Rport: rf.BindPort,
Laddr: originatorAddress,
Lport: originatorPort,
}
b := ssh.Marshal(&drtMsg)
destination, reqs, err := sshConn.OpenChannel("forwarded-tcpip", b)
if err != nil {
log.Println("Opening forwarded-tcpip channel to server failed: ", err)
return err
}
defer destination.Close()
go ssh.DiscardRequests(reqs)
log.Println("Forwarded-tcpip channel request sent and accepted")
go func() {
defer destination.Close()
defer proxyCon.Close()
io.Copy(destination, proxyCon)
}()
defer proxyCon.Close()
_, err = io.Copy(proxyCon, destination)
return err
}