Repository navigation
Expand file tree
/
Copy pathssh_tunnel.go
More file actions
191 lines (164 loc) Β· 4.31 KB
/
Copy pathssh_tunnel.go
File metadata and controls
191 lines (164 loc) Β· 4.31 KB
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
package sshtunnel
import (
"io"
"net"
"golang.org/x/crypto/ssh"
)
type logger interface {
Printf(string, ...interface{})
}
type SSHTunnel struct {
Local *Endpoint
Server *Endpoint
Remote *Endpoint
Config *ssh.ClientConfig
Log logger
Conns []net.Conn
SvrConns []*ssh.Client
MaxConnectionAttempts int
isOpen bool
listener net.Listener
close chan interface{}
}
func (tunnel *SSHTunnel) logf(fmt string, args ...interface{}) {
if tunnel.Log != nil {
tunnel.Log.Printf(fmt, args...)
}
}
func newConnectionWaiter(listener net.Listener, c chan net.Conn) {
conn, err := listener.Accept()
if err != nil {
return
}
c <- conn
}
func (tunnel *SSHTunnel) Initialize() error {
listener, err := net.Listen("tcp", tunnel.Local.String())
if err != nil {
return err
}
tunnel.isOpen = true
tunnel.listener = listener
tunnel.Local.Port = listener.Addr().(*net.TCPAddr).Port
return nil
}
func (tunnel *SSHTunnel) Start() error {
if tunnel.listener == nil {
if err := tunnel.Initialize(); err != nil {
return err
}
}
var listener = tunnel.listener
// Ensure that MaxConnectionAttempts is at least 1. This check is done here
// since the library user can set the value at any point before Start() is called,
// and this check protects against the case where the programmer set MaxConnectionAttempts
// to 0 for some reason.
if tunnel.MaxConnectionAttempts <= 0 {
tunnel.MaxConnectionAttempts = 1
}
for {
if !tunnel.isOpen {
break
}
c := make(chan net.Conn)
go newConnectionWaiter(listener, c)
tunnel.logf("listening for new connections...")
select {
case <-tunnel.close:
tunnel.logf("close signal received, closing...")
tunnel.isOpen = false
tunnel.listener = nil
case conn := <-c:
tunnel.Conns = append(tunnel.Conns, conn)
tunnel.logf("accepted connection")
go tunnel.forward(conn)
}
}
var total int
total = len(tunnel.Conns)
for i, conn := range tunnel.Conns {
tunnel.logf("closing the netConn (%d of %d)", i+1, total)
err := conn.Close()
if err != nil {
tunnel.logf(err.Error())
}
}
total = len(tunnel.SvrConns)
for i, conn := range tunnel.SvrConns {
tunnel.logf("closing the serverConn (%d of %d)", i+1, total)
err := conn.Close()
if err != nil {
tunnel.logf(err.Error())
}
}
err := listener.Close()
if err != nil {
return err
}
tunnel.logf("tunnel closed")
return nil
}
func (tunnel *SSHTunnel) forward(localConn net.Conn) {
var (
serverConn *ssh.Client
err error
attemptsLeft int = tunnel.MaxConnectionAttempts
)
for {
serverConn, err = ssh.Dial("tcp", tunnel.Server.String(), tunnel.Config)
if err != nil {
attemptsLeft--
if attemptsLeft <= 0 {
tunnel.logf("server dial error: %v: exceeded %d attempts", err, tunnel.MaxConnectionAttempts)
return
}
} else {
break
}
}
tunnel.logf("connected to %s (1 of 2)\n", tunnel.Server.String())
tunnel.SvrConns = append(tunnel.SvrConns, serverConn)
remoteConn, err := serverConn.Dial("tcp", tunnel.Remote.String())
if err != nil {
tunnel.logf("remote dial error: %s", err)
return
}
tunnel.Conns = append(tunnel.Conns, remoteConn)
tunnel.logf("connected to %s (2 of 2)\n", tunnel.Remote.String())
copyConn := func(writer, reader net.Conn) {
_, err := io.Copy(writer, reader)
if err != nil {
tunnel.logf("io.Copy error: %s", err)
}
}
go copyConn(localConn, remoteConn)
go copyConn(remoteConn, localConn)
return
}
func (tunnel *SSHTunnel) Close() {
tunnel.close <- struct{}{}
return
}
// NewSSHTunnel creates a new single-use tunnel. Supplying "0" for localport will use a random port.
func NewSSHTunnel(tunnel string, auth ssh.AuthMethod, destination string, localport string) *SSHTunnel {
localEndpoint := NewEndpoint("localhost:" + localport)
server := NewEndpoint(tunnel)
if server.Port == 0 {
server.Port = 22
}
sshTunnel := &SSHTunnel{
Config: &ssh.ClientConfig{
User: server.User,
Auth: []ssh.AuthMethod{auth},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
// Always accept key.
return nil
},
},
Local: localEndpoint,
Server: server,
Remote: NewEndpoint(destination),
close: make(chan interface{}),
}
return sshTunnel
}