-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathservice.go
More file actions
377 lines (347 loc) · 9.95 KB
/
Copy pathservice.go
File metadata and controls
377 lines (347 loc) · 9.95 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
Copyright (C) 2025 dyhkwong
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package juicity
import (
"context"
"crypto/hmac"
"encoding/hex"
"errors"
"io"
"net"
"runtime"
"sync"
"time"
"github.com/sagernet/quic-go"
"github.com/sagernet/sing-quic"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
"github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/logger"
"github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/tls"
)
type ServiceOptions struct {
Context context.Context
Logger logger.Logger
TLSConfig tls.ServerConfig
QUICConfig *quic.Config
QUICOptions qtls.QUICOptions
CongestionControl string
AuthTimeout time.Duration
// UDPTimeout time.Duration todo?
Handler ServiceHandler
}
type ServiceHandler interface {
network.TCPConnectionHandlerEx
network.UDPConnectionHandlerEx
}
type Service[U comparable] struct {
ctx context.Context
logger logger.Logger
tlsConfig tls.ServerConfig
quicConfig *quic.Config
userMap map[[16]byte]U
passwordMap map[U]string
congestionControl string
authTimeout time.Duration
handler ServiceHandler
quicListener io.Closer
}
func NewService[U comparable](options ServiceOptions) (*Service[U], error) {
if options.AuthTimeout == 0 {
// Official Juicity server uses 10 seconds
options.AuthTimeout = 10 * time.Second
}
quicConfig := options.QUICConfig
if quicConfig == nil {
quicConfig = &quic.Config{
DisablePathMTUDiscovery: !(runtime.GOOS == "windows" || runtime.GOOS == "linux" || runtime.GOOS == "android" || runtime.GOOS == "darwin"),
MaxIncomingStreams: 1 << 60,
}
qtls.ApplyQUICOptions(quicConfig, options.QUICOptions)
}
congestionControl := options.CongestionControl
switch congestionControl {
case "":
congestionControl = "bbr"
case "cubic", "new_reno", "bbr", "bbr2":
case "bbr_meta_v1", "bbr_quiche", "bbr2_aggressive":
// sing-quic private names
default:
return nil, exceptions.New("unknown congestion control algorithm: ", options.CongestionControl)
}
return &Service[U]{
ctx: options.Context,
logger: options.Logger,
tlsConfig: options.TLSConfig, // servers need to set ALPN `h3` themselves
quicConfig: quicConfig,
userMap: make(map[[16]byte]U),
congestionControl: congestionControl,
authTimeout: options.AuthTimeout,
handler: options.Handler,
}, nil
}
func (s *Service[U]) UpdateUsers(userList []U, uuidList [][16]byte, passwordList []string) {
userMap := make(map[[16]byte]U)
passwordMap := make(map[U]string)
for index := range userList {
userMap[uuidList[index]] = userList[index]
passwordMap[userList[index]] = passwordList[index]
}
s.userMap = userMap
s.passwordMap = passwordMap
}
func (s *Service[U]) Start(conn net.PacketConn) error {
listener, err := qtls.Listen(conn, s.tlsConfig, s.quicConfig)
if err != nil {
return err
}
s.quicListener = listener
go func() {
for {
connection, hErr := listener.Accept(s.ctx)
if hErr != nil {
if exceptions.IsClosedOrCanceled(hErr) || errors.Is(hErr, quic.ErrServerClosed) {
s.logger.Debug(exceptions.Cause(hErr, "listener closed"))
} else {
s.logger.Error(exceptions.Cause(hErr, "listener closed"))
}
return
}
go s.handleConnection(connection)
}
}()
return nil
}
func (s *Service[U]) Close() error {
return common.Close(
s.quicListener,
)
}
func (s *Service[U]) handleConnection(connection *quic.Conn) {
setCongestion(s.ctx, connection, s.congestionControl)
session := &serverSession[U]{
Service: s,
ctx: s.ctx,
quicConn: connection,
connDone: make(chan struct{}),
authDone: make(chan struct{}),
}
session.handle()
}
type serverSession[U comparable] struct {
*Service[U]
ctx context.Context
quicConn *quic.Conn
connAccess sync.Mutex
connDone chan struct{}
connErr error
authDone chan struct{}
authUser U
}
func (s *serverSession[U]) handle() {
if s.ctx.Done() != nil {
go func() {
select {
case <-s.ctx.Done():
s.closeWithError(s.ctx.Err())
case <-s.connDone:
}
}()
}
go s.loopUniStreams()
go s.loopStreams()
go s.handleAuthTimeout()
}
func (s *serverSession[U]) loopUniStreams() {
for {
uniStream, err := s.quicConn.AcceptUniStream(s.ctx)
if err != nil {
return
}
go func() {
err = s.handleUniStream(uniStream)
if err != nil {
s.closeWithError(exceptions.Cause(err, "handle uni stream"))
}
}()
}
}
func (s *serverSession[U]) handleUniStream(stream *quic.ReceiveStream) error {
defer stream.CancelRead(0)
buffer := buf.New()
defer buffer.Release()
_, err := buffer.ReadAtLeastFrom(stream, 2)
if err != nil {
return exceptions.Cause(err, "read request")
}
version := buffer.Byte(0)
if version != Version {
return exceptions.New("unknown version ", buffer.Byte(0))
}
command := buffer.Byte(1)
switch command {
case CommandAuthenticate:
select {
case <-s.authDone:
return exceptions.New("authentication: multiple authentication requests")
default:
}
if buffer.Len() < AuthenticateLen {
_, err = buffer.ReadFullFrom(stream, AuthenticateLen-buffer.Len())
if err != nil {
return exceptions.Cause(err, "authentication: read request")
}
}
var userUUID [16]byte
copy(userUUID[:], buffer.Range(2, 2+16))
user, loaded := s.userMap[userUUID]
if !loaded {
return exceptions.New("authentication: unknown user ", uuidToString(userUUID))
}
handshakeState := s.quicConn.ConnectionState()
token, err := handshakeState.TLS.ExportKeyingMaterial(string(userUUID[:]), []byte(s.passwordMap[user]), 32)
if err != nil {
return exceptions.Cause(err, "authentication: export keying material")
}
if !hmac.Equal(token, buffer.Range(2+16, AuthenticateLen)) {
return exceptions.New("authentication: token mismatch")
}
s.authUser = user
close(s.authDone)
return nil
default:
return exceptions.New("unknown command ", command)
}
}
func (s *serverSession[U]) handleAuthTimeout() {
select {
case <-s.connDone:
case <-s.authDone:
case <-time.After(s.authTimeout):
s.closeWithError(exceptions.New("authentication timeout"))
}
}
func (s *serverSession[U]) loopStreams() {
for {
stream, err := s.quicConn.AcceptStream(s.ctx)
if err != nil {
return
}
go func() {
err = s.handleStream(stream)
if err != nil {
stream.CancelRead(0)
stream.Close()
s.logger.Error(exceptions.Cause(err, "handle stream request"))
}
}()
}
}
func (s *serverSession[U]) handleStream(stream *quic.Stream) error {
// Most of the vulnerabilities described in https://github.com/tuic-protocol/tuic/issues/67#issuecomment-1196862427 are still valid.
// Unable to fix because they are design flaw.
buffer := buf.NewSize(1 + metadata.MaxSocksaddrLength)
defer buffer.Release()
_, err := buffer.ReadAtLeastFrom(stream, 1)
if err != nil {
return exceptions.Cause(err, "read request")
}
network, _ := buffer.ReadByte()
if network != NetworkTCP && network != NetworkUDP {
return exceptions.New("unsupported stream network")
}
destination, err := AddressSerializer.ReadAddrPort(io.MultiReader(buffer, stream))
if err != nil {
return exceptions.Cause(err, "read request destination")
}
select {
case <-s.connDone:
return s.connErr
case <-s.authDone:
}
var conn net.Conn = &serverConn{
Stream: stream,
destination: destination,
}
if !buffer.IsEmpty() {
conn = bufio.NewCachedConn(conn, buffer.ToOwned())
}
switch network {
case NetworkTCP:
s.handler.NewConnectionEx(auth.ContextWithUser(s.ctx, s.authUser), conn, metadata.SocksaddrFromNet(s.quicConn.RemoteAddr()).Unwrap(), destination, nil)
case NetworkUDP:
s.handler.NewPacketConnectionEx(auth.ContextWithUser(s.ctx, s.authUser), &udpPacketConn{Conn: conn}, metadata.SocksaddrFromNet(s.quicConn.RemoteAddr()).Unwrap(), destination, nil)
}
return nil
}
func (s *serverSession[U]) closeWithError(err error) {
s.connAccess.Lock()
defer s.connAccess.Unlock()
select {
case <-s.connDone:
return
default:
s.connErr = err
close(s.connDone)
}
if exceptions.IsClosedOrCanceled(err) {
s.logger.Debug(exceptions.Cause(err, "connection failed"))
} else {
s.logger.Error(exceptions.Cause(err, "connection failed"))
}
_ = s.quicConn.CloseWithError(0, "")
}
type serverConn struct {
*quic.Stream
destination metadata.Socksaddr
}
func (c *serverConn) Read(p []byte) (int, error) {
n, err := c.Stream.Read(p)
return n, wrapQUICError(err)
}
func (c *serverConn) Write(p []byte) (int, error) {
n, err := c.Stream.Write(p)
return n, wrapQUICError(err)
}
func (c *serverConn) LocalAddr() net.Addr {
return c.destination
}
func (c *serverConn) RemoteAddr() net.Addr {
return metadata.Socksaddr{}
}
func (c *serverConn) Close() error {
c.Stream.CancelRead(0)
err := c.Stream.Close()
// quic-go's Stream.Close does not unblock a Write blocked on flow control,
// but a past write deadline does; buffered data and the FIN are unaffected.
c.Stream.SetWriteDeadline(time.Now())
return err
}
func uuidToString(uuid [16]byte) string {
var buf [36]byte
hex.Encode(buf[:8], uuid[:4])
buf[8] = '-'
hex.Encode(buf[9:13], uuid[4:6])
buf[13] = '-'
hex.Encode(buf[14:18], uuid[6:8])
buf[18] = '-'
hex.Encode(buf[19:23], uuid[8:10])
buf[23] = '-'
hex.Encode(buf[24:], uuid[10:])
return string(buf[:])
}