-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathsocks5.go
More file actions
254 lines (212 loc) · 6.53 KB
/
Copy pathsocks5.go
File metadata and controls
254 lines (212 loc) · 6.53 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package service
import (
"context"
"errors"
"fmt"
"net"
"slices"
"strings"
"time"
socks5Proxy "github.com/haxii/socks5"
"github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/network"
"github.com/anywherelan/awl/config"
"github.com/anywherelan/awl/entity"
"github.com/anywherelan/awl/metrics"
"github.com/anywherelan/awl/protocol"
"github.com/anywherelan/awl/socks5"
)
type SOCKS5 struct {
logger *log.ZapEventLogger
p2p P2p
conf *config.Config
client *socks5.Client
server *socks5.Server
}
func NewSOCKS5(p2pService P2p, conf *config.Config) (*SOCKS5, error) {
logger := log.Logger("awl/service/socks5")
var client *socks5.Client
if conf.SOCKS5.ListenerEnabled {
var err error
client, err = socks5.NewClient(conf.SOCKS5.ListenAddress, conf.SOCKS5.Username, conf.SOCKS5.Password)
if err != nil {
return nil, fmt.Errorf("failed to start socks5 listener: %v", err)
}
logger.Infof("started socks5 proxy on socks5://%s", conf.SOCKS5.ListenAddress)
}
server := socks5.NewServer()
socks := &SOCKS5{
logger: logger,
p2p: p2pService,
conf: conf,
client: client,
server: server,
}
return socks, nil
}
func (s *SOCKS5) Close() {
if s.client != nil {
_ = s.client.Close()
}
}
func (s *SOCKS5) ListAvailableProxies() []entity.AvailableProxy {
s.conf.RLock()
proxies := []entity.AvailableProxy{}
for _, peer := range s.conf.KnownPeers {
if !peer.AllowedUsingAsExitNode {
continue
}
if !s.p2p.IsConnected(peer.PeerId()) {
continue
}
proxy := entity.AvailableProxy{
PeerID: peer.PeerID,
PeerName: peer.DisplayName(),
}
proxies = append(proxies, proxy)
}
s.conf.RUnlock()
slices.SortFunc(proxies, func(a, b entity.AvailableProxy) int {
return strings.Compare(a.PeerName, b.PeerName)
})
return proxies
}
func (s *SOCKS5) SetProxyPeerID(peerID string) {
s.conf.Lock()
s.conf.SOCKS5.UsingPeerID = peerID
s.conf.Unlock()
s.conf.Save()
}
func (s *SOCKS5) GetProxyPeerID() string {
s.conf.RLock()
defer s.conf.RUnlock()
return s.conf.SOCKS5.UsingPeerID
}
func (s *SOCKS5) ProxyStreamHandler(stream network.Stream) {
metrics.SOCKS5ConnectionsTotal.WithLabelValues("server").Inc()
metrics.SOCKS5ActiveConnections.WithLabelValues("server").Inc()
start := time.Now()
defer func() {
metrics.SOCKS5ActiveConnections.WithLabelValues("server").Dec()
metrics.SOCKS5ConnectionDurationSeconds.WithLabelValues("server").Observe(time.Since(start).Seconds())
_ = stream.Reset()
}()
remotePeer := stream.Conn().RemotePeer()
peerID := remotePeer.String()
knownPeer, known := s.conf.GetPeer(peerID)
if !known {
metrics.SOCKS5ErrorsTotal.WithLabelValues("server", "denied").Inc()
s.logger.Infof("Unknown peer %s tried to socks5 proxy", peerID)
return
}
if !knownPeer.WeAllowUsingAsExitNode {
metrics.SOCKS5ErrorsTotal.WithLabelValues("server", "denied").Inc()
s.logger.Infof("Peer %s without rights tried to socks5 proxy", peerID)
return
}
s.conf.RLock()
enabled := s.conf.SOCKS5.ProxyingEnabled
s.conf.RUnlock()
if !enabled {
metrics.SOCKS5ErrorsTotal.WithLabelValues("server", "proxying_disabled").Inc()
if stream.Protocol() != protocol.Socks5NoAuthMethod {
_ = s.server.SendServerFailureReply(stream)
}
return
}
// ignore error, we can do nothing about it
if stream.Protocol() == protocol.Socks5NoAuthMethod {
_ = s.server.ServeStreamConnNoAuth(stream)
} else {
_ = s.server.ServeStreamConn(stream)
}
// stream.Write() + stream.Reset() are not guaranteed to run sequentially
// e.g reader on the other side may not read everything we sent because of stream.Reset()
// in case of socks5 errors (small payload), receiver could get EOF
// TODO: make better workaround for this. stream.CloseWrite(), etc doesn't help
time.Sleep(50 * time.Millisecond)
}
func (s *SOCKS5) ServeConns(ctx context.Context) {
if s.client == nil {
return
}
proxyConns := s.client.ConnsChan()
for conn := range proxyConns {
go func() {
defer func() {
_ = conn.Close()
}()
s.logger.Debug("got new SOCKS5 proxy client connection")
err := s.proxyConn(ctx, conn)
if err != nil {
_ = s.server.SendServerFailureReply(conn)
}
}()
}
}
// SetProxyingLocalhostEnabled is created for tests and not intended for real usage.
func (s *SOCKS5) SetProxyingLocalhostEnabled(enabled bool) {
if enabled {
s.server.SetRules(socks5.NewRulePermitAll())
} else {
s.server.SetRules(socks5.NewRuleDenyLocalhost())
}
}
func (s *SOCKS5) proxyConn(ctx context.Context, conn net.Conn) error {
metrics.SOCKS5ConnectionsTotal.WithLabelValues("client").Inc()
metrics.SOCKS5ActiveConnections.WithLabelValues("client").Inc()
start := time.Now()
defer func() {
metrics.SOCKS5ActiveConnections.WithLabelValues("client").Dec()
metrics.SOCKS5ConnectionDurationSeconds.WithLabelValues("client").Observe(time.Since(start).Seconds())
}()
s.conf.RLock()
usePeerID := s.conf.SOCKS5.UsingPeerID
s.conf.RUnlock()
if usePeerID == "" {
metrics.SOCKS5ErrorsTotal.WithLabelValues("client", "no_proxy_peer").Inc()
return errors.New("no peer is set for proxy")
}
peer, exists := s.conf.GetPeer(usePeerID)
if !exists || !peer.AllowedUsingAsExitNode {
metrics.SOCKS5ErrorsTotal.WithLabelValues("client", "peer_not_allowed").Inc()
return fmt.Errorf("configured proxy peer %s does not allow us to proxy traffic", usePeerID)
}
remotePeerID := peer.PeerId()
err := s.p2p.ConnectPeer(ctx, remotePeerID)
if err != nil {
metrics.SOCKS5ErrorsTotal.WithLabelValues("client", "peer_connect_failed").Inc()
return err
}
stream, err := s.p2p.NewStreamMulti(ctx, remotePeerID, protocol.Socks5NoAuthMethod, protocol.Socks5PacketMethod)
if err != nil {
metrics.SOCKS5ErrorsTotal.WithLabelValues("client", "peer_stream_failed").Inc()
return err
}
defer func() {
_ = stream.Reset()
}()
if stream.Protocol() == protocol.Socks5NoAuthMethod {
if err := s.client.HandleLocalAuth(conn); err != nil {
return err
}
}
s.handleStream(conn, stream)
// stream.Write() + stream.Reset() are not guaranteed to run sequentially
// e.g reader on the other side may not read everything we sent because of stream.Reset()
// in case of socks5 errors (small payload), receiver could get EOF
// TODO: make better workaround for this. stream.CloseWrite(), etc doesn't help
time.Sleep(50 * time.Millisecond)
return nil
}
func (s *SOCKS5) handleStream(conn net.Conn, stream network.Stream) {
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
// Copy from conn to stream
_ = socks5Proxy.ProxyStream(conn, stream)
}()
// Copy from stream to conn
_ = socks5Proxy.ProxyStream(stream, conn)
<-doneCh
}