-
Notifications
You must be signed in to change notification settings - Fork 4k
/
protocol.go
351 lines (293 loc) · 9.35 KB
/
protocol.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
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
package shadowsocks
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
goerrors "errors"
"hash/crc32"
"io"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/drain"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
)
const (
Version = 1
)
var addrParser = protocol.NewAddressParser(
protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
protocol.WithAddressTypeParser(func(b byte) byte {
return b & 0x0F
}),
)
type FullReader struct {
reader io.Reader
buffer []byte
}
func (r *FullReader) Read(p []byte) (n int, err error) {
if r.buffer != nil {
n := copy(p, r.buffer)
if n == len(r.buffer) {
r.buffer = nil
} else {
r.buffer = r.buffer[n:]
}
if n == len(p) {
return n, nil
} else {
m, err := r.reader.Read(p[n:])
return n + m, err
}
}
return r.reader.Read(p)
}
// ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts.
func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
behaviorSeed := validator.GetBehaviorSeed()
drainer, errDrain := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if errDrain != nil {
return nil, nil, errors.New("failed to initialize drainer").Base(errDrain)
}
var r buf.Reader
buffer := buf.New()
defer buffer.Release()
if _, err := buffer.ReadFullFrom(reader, 50); err != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, errors.New("failed to read 50 bytes").Base(err))
}
bs := buffer.Bytes()
user, aead, _, ivLen, err := validator.Get(bs, protocol.RequestCommandTCP)
switch err {
case ErrNotFound:
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, errors.New("failed to match an user").Base(err))
case ErrIVNotUnique:
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, errors.New("failed iv check").Base(err))
default:
reader = &FullReader{reader, bs[ivLen:]}
drainer.AcknowledgeReceive(int(ivLen))
if aead != nil {
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: crypto.GenerateAEADNonceWithSize(aead.NonceSize()),
}
r = crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{
Auth: auth,
}, reader, protocol.TransferTypeStream, nil)
} else {
account := user.Account.(*MemoryAccount)
iv := append([]byte(nil), buffer.BytesTo(ivLen)...)
r, err = account.Cipher.NewDecryptionReader(account.Key, iv, reader)
if err != nil {
return nil, nil, drain.WithError(drainer, reader, errors.New("failed to initialize decoding stream").Base(err).AtError())
}
}
}
br := &buf.BufferedReader{Reader: r}
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandTCP,
}
buffer.Clear()
addr, port, err := addrParser.ReadAddressPort(buffer, br)
if err != nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, errors.New("failed to read address").Base(err))
}
request.Address = addr
request.Port = port
if request.Address == nil {
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, errors.New("invalid remote address."))
}
return request, br, nil
}
// WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
if ivError := account.CheckIV(iv); ivError != nil {
return nil, errors.New("failed to mark outgoing iv").Base(ivError)
}
if err := buf.WriteAllBytes(writer, iv, nil); err != nil {
return nil, errors.New("failed to write IV")
}
}
w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
if err != nil {
return nil, errors.New("failed to create encoding stream").Base(err).AtError()
}
header := buf.New()
if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil {
return nil, errors.New("failed to write address").Base(err)
}
if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil {
return nil, errors.New("failed to write header").Base(err)
}
return w, nil
}
func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) {
account := user.Account.(*MemoryAccount)
hashkdf := hmac.New(sha256.New, []byte("SSBSKDF"))
hashkdf.Write(account.Key)
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if err != nil {
return nil, errors.New("failed to initialize drainer").Base(err)
}
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
if n, err := io.ReadFull(reader, iv); err != nil {
return nil, errors.New("failed to read IV").Base(err)
} else { // nolint: golint
drainer.AcknowledgeReceive(n)
}
}
if ivError := account.CheckIV(iv); ivError != nil {
return nil, drain.WithError(drainer, reader, errors.New("failed iv check").Base(ivError))
}
return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
}
func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
common.Must2(rand.Read(iv))
if ivError := account.CheckIV(iv); ivError != nil {
return nil, errors.New("failed to mark outgoing iv").Base(ivError)
}
if err := buf.WriteAllBytes(writer, iv, nil); err != nil {
return nil, errors.New("failed to write IV.").Base(err)
}
}
return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
}
func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
user := request.User
account := user.Account.(*MemoryAccount)
buffer := buf.New()
ivLen := account.Cipher.IVSize()
if ivLen > 0 {
common.Must2(buffer.ReadFullFrom(rand.Reader, ivLen))
}
if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil {
return nil, errors.New("failed to write address").Base(err)
}
buffer.Write(payload)
if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
return nil, errors.New("failed to encrypt UDP payload").Base(err)
}
return buffer, nil
}
func DecodeUDPPacket(validator *Validator, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
rawPayload := payload.Bytes()
user, _, d, _, err := validator.Get(rawPayload, protocol.RequestCommandUDP)
if goerrors.Is(err, ErrIVNotUnique) {
return nil, nil, errors.New("failed iv check").Base(err)
}
if goerrors.Is(err, ErrNotFound) {
return nil, nil, errors.New("failed to match an user").Base(err)
}
if err != nil {
return nil, nil, errors.New("unexpected error").Base(err)
}
account, ok := user.Account.(*MemoryAccount)
if !ok {
return nil, nil, errors.New("expected MemoryAccount returned from validator")
}
if account.Cipher.IsAEAD() {
payload.Clear()
payload.Write(d)
} else {
if account.Cipher.IVSize() > 0 {
iv := make([]byte, account.Cipher.IVSize())
copy(iv, payload.BytesTo(account.Cipher.IVSize()))
}
if err = account.Cipher.DecodePacket(account.Key, payload); err != nil {
return nil, nil, errors.New("failed to decrypt UDP payload").Base(err)
}
}
payload.SetByte(0, payload.Byte(0)&0x0F)
addr, port, err := addrParser.ReadAddressPort(nil, payload)
if err != nil {
return nil, nil, errors.New("failed to parse address").Base(err)
}
request := &protocol.RequestHeader{
Version: Version,
User: user,
Command: protocol.RequestCommandUDP,
Address: addr,
Port: port,
}
return request, payload, nil
}
type UDPReader struct {
Reader io.Reader
User *protocol.MemoryUser
}
func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
buffer := buf.New()
_, err := buffer.ReadFrom(v.Reader)
if err != nil {
buffer.Release()
return nil, err
}
validator := new(Validator)
validator.Add(v.User)
u, payload, err := DecodeUDPPacket(validator, buffer)
if err != nil {
buffer.Release()
return nil, err
}
dest := u.Destination()
payload.UDP = &dest
return buf.MultiBuffer{payload}, nil
}
type UDPWriter struct {
Writer io.Writer
Request *protocol.RequestHeader
}
func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
for {
mb2, b := buf.SplitFirst(mb)
mb = mb2
if b == nil {
break
}
request := w.Request
if b.UDP != nil {
request = &protocol.RequestHeader{
User: w.Request.User,
Address: b.UDP.Address,
Port: b.UDP.Port,
}
}
packet, err := EncodeUDPPacket(request, b.Bytes())
b.Release()
if err != nil {
buf.ReleaseMulti(mb)
return err
}
_, err = w.Writer.Write(packet.Bytes())
packet.Release()
if err != nil {
buf.ReleaseMulti(mb)
return err
}
}
return nil
}