/
listner.go
101 lines (65 loc) · 2.04 KB
/
listner.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
package tunnel
import (
"io"
"log"
"net"
"golang.org/x/crypto/ssh"
)
const (
sshPort = "22"
)
// LocalListner start listner on the local address and call Forward function
func LocalListner(cleintTarget *ssh.Client, localAddress string, remoteAddress string) {
listener, err := net.Listen("tcp", localAddress)
if err != nil {
panic(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
panic(err)
}
if conn == nil {
panic("conn is nil")
}
Forward(cleintTarget, conn, remoteAddress)
}
}
// Forward dial to the target client and start io.copy fron local-remote and remote-local
func Forward(cleintTarget *ssh.Client, localConn net.Conn, remoteAddress string) {
remoteConn, err := cleintTarget.Dial("tcp", remoteAddress)
if err != nil {
localConn.Close()
if remoteConn != nil {
remoteConn.Close()
}
panic(err)
}
copyConn := func(writer, reader net.Conn) {
if writer != nil {
if reader != nil {
_, err := io.Copy(writer, reader)
if err != nil {
log.Println("copyConn - err: ", err)
writer.Close()
reader.Close()
}
}
}
return
}
go copyConn(localConn, remoteConn)
go copyConn(remoteConn, localConn)
}
// ListenOverMiddle creates SSH tunnel over middle machine
func ListenOverMiddle(userBastion string, userTarget string, bastionKey string, targetKey string, bastionAddress string, TargetAddress, localListnerAddr string, remoteListnerAddr string) {
clientBastion := FirstClient(userBastion, bastionKey, bastionAddress, sshPort, "key")
cleintTarget := TargetClient(clientBastion, userTarget, targetKey, TargetAddress, sshPort, "key")
LocalListner(cleintTarget, localListnerAddr, remoteListnerAddr)
}
// ListenDirect creates SSH tunnel directly to the remote machine
func ListenDirect(targetKey string, userTarget string, TargetAddress, localListnerAddr string, remoteListnerAddr string) {
cleintTarget := FirstClient(userTarget, targetKey, TargetAddress, sshPort, "key")
LocalListner(cleintTarget, localListnerAddr, remoteListnerAddr)
}