-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
tunnel.go
190 lines (180 loc) · 4.22 KB
/
tunnel.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
package tunnel
import (
"bytes"
"context"
"errors"
"io/ioutil"
"log"
"os"
"sync"
"time"
"github.com/armon/go-socks5"
"github.com/jpillora/chisel/share/cio"
"github.com/jpillora/chisel/share/cnet"
"github.com/jpillora/chisel/share/settings"
"golang.org/x/crypto/ssh"
"golang.org/x/sync/errgroup"
)
//Config a Tunnel
type Config struct {
*cio.Logger
Inbound bool
Outbound bool
Socks bool
KeepAlive time.Duration
}
//Tunnel represents an SSH tunnel with proxy capabilities.
//Both chisel client and server are Tunnels.
//chisel client has a single set of remotes, whereas
//chisel server has multiple sets of remotes (one set per client).
//Each remote has a 1:1 mapping to a proxy.
//Proxies listen, send data over ssh, and the other end of the ssh connection
//communicates with the endpoint and returns the response.
type Tunnel struct {
Config
//ssh connection
activeConnMut sync.RWMutex
activatingConn waitGroup
activeConn ssh.Conn
//proxies
proxyCount int
//internals
connStats cnet.ConnCount
socksServer *socks5.Server
}
//New Tunnel from the given Config
func New(c Config) *Tunnel {
c.Logger = c.Logger.Fork("tun")
t := &Tunnel{
Config: c,
}
t.activatingConn.Add(1)
//setup socks server (not listening on any port!)
extra := ""
if c.Socks {
sl := log.New(ioutil.Discard, "", 0)
if t.Logger.Debug {
sl = log.New(os.Stdout, "[socks]", log.Ldate|log.Ltime)
}
t.socksServer, _ = socks5.New(&socks5.Config{Logger: sl})
extra += " (SOCKS enabled)"
}
t.Debugf("Created%s", extra)
return t
}
//BindSSH provides an active SSH for use for tunnelling
func (t *Tunnel) BindSSH(ctx context.Context, c ssh.Conn, reqs <-chan *ssh.Request, chans <-chan ssh.NewChannel) error {
//link ctx to ssh-conn
go func() {
<-ctx.Done()
if c.Close() == nil {
t.Debugf("SSH cancelled")
}
t.activatingConn.DoneAll()
}()
//mark active and unblock
t.activeConnMut.Lock()
if t.activeConn != nil {
panic("double bind ssh")
}
t.activeConn = c
t.activeConnMut.Unlock()
t.activatingConn.Done()
//optional keepalive loop against this connection
if t.Config.KeepAlive > 0 {
go t.keepAliveLoop(c)
}
//block until closed
go t.handleSSHRequests(reqs)
go t.handleSSHChannels(chans)
t.Debugf("SSH connected")
err := c.Wait()
t.Debugf("SSH disconnected")
//mark inactive and block
t.activatingConn.Add(1)
t.activeConnMut.Lock()
t.activeConn = nil
t.activeConnMut.Unlock()
return err
}
//getSSH blocks while connecting
func (t *Tunnel) getSSH(ctx context.Context) ssh.Conn {
//cancelled already?
if isDone(ctx) {
return nil
}
t.activeConnMut.RLock()
c := t.activeConn
t.activeConnMut.RUnlock()
//connected already?
if c != nil {
return c
}
//connecting...
select {
case <-ctx.Done(): //cancelled
return nil
case <-time.After(35 * time.Second): //a bit longer than ssh timeout
return nil
case <-t.activatingConnWait():
t.activeConnMut.RLock()
c := t.activeConn
t.activeConnMut.RUnlock()
return c
}
}
func (t *Tunnel) activatingConnWait() <-chan struct{} {
ch := make(chan struct{})
go func() {
t.activatingConn.Wait()
close(ch)
}()
return ch
}
//BindRemotes converts the given remotes into proxies, and blocks
//until the caller cancels the context or there is a proxy error.
func (t *Tunnel) BindRemotes(ctx context.Context, remotes []*settings.Remote) error {
if len(remotes) == 0 {
return errors.New("no remotes")
}
if !t.Inbound {
return errors.New("inbound connections blocked")
}
proxies := make([]*Proxy, len(remotes))
for i, remote := range remotes {
p, err := NewProxy(t.Logger, t, t.proxyCount, remote)
if err != nil {
return err
}
proxies[i] = p
t.proxyCount++
}
//TODO: handle tunnel close
eg, ctx := errgroup.WithContext(ctx)
for _, proxy := range proxies {
p := proxy
eg.Go(func() error {
return p.Run(ctx)
})
}
t.Debugf("Bound proxies")
err := eg.Wait()
t.Debugf("Unbound proxies")
return err
}
func (t *Tunnel) keepAliveLoop(sshConn ssh.Conn) {
//ping forever
for {
time.Sleep(t.Config.KeepAlive)
_, b, err := sshConn.SendRequest("ping", true, nil)
if err != nil {
break
}
if len(b) > 0 && !bytes.Equal(b, []byte("pong")) {
t.Debugf("strange ping response")
break
}
}
//close ssh connection on abnormal ping
sshConn.Close()
}