-
Notifications
You must be signed in to change notification settings - Fork 19
/
stream.go
402 lines (337 loc) · 11.3 KB
/
stream.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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package ss2022
import (
"bytes"
"crypto/cipher"
"crypto/rand"
"encoding/binary"
"errors"
"io"
"github.com/database64128/shadowsocks-go/zerocopy"
)
const MaxPayloadSize = 0xFFFF
// ShadowStreamHeadroom is the headroom required by an encrypted Shadowsocks stream.
//
// Front is the size of an encrypted length chunk.
// Rear is the size of an AEAD tag.
var ShadowStreamHeadroom = zerocopy.Headroom{
Front: 2 + 16,
Rear: 16,
}
// ShadowStreamReaderInfo contains information about a [ShadowStreamReader].
var ShadowStreamReaderInfo = zerocopy.ReaderInfo{
Headroom: ShadowStreamHeadroom,
MinPayloadBufferSizePerRead: MaxPayloadSize,
}
// ShadowStreamWriterInfo contains information about a [ShadowStreamWriter].
var ShadowStreamWriterInfo = zerocopy.WriterInfo{
Headroom: ShadowStreamHeadroom,
MaxPayloadSizePerWrite: MaxPayloadSize,
}
var (
ErrZeroLengthChunk = errors.New("length in length chunk is zero")
ErrFirstRead = errors.New("failed to read fixed-length header in one read call")
ErrRepeatedSalt = errors.New("detected replay: repeated salt")
)
var ErrUnsafeStreamPrefixMismatch = errors.New("unsafe stream prefix mismatch")
// ShadowStreamServerReadWriter implements Shadowsocks stream server.
type ShadowStreamServerReadWriter struct {
*ShadowStreamReader
*ShadowStreamWriter
rawRW zerocopy.DirectReadWriteCloser
cipherConfig UserCipherConfig
requestSalt []byte
unsafeResponseStreamPrefix []byte
}
// WriteZeroCopy implements the Writer WriteZeroCopy method.
func (rw *ShadowStreamServerReadWriter) WriteZeroCopy(b []byte, payloadStart, payloadLen int) (int, error) {
if rw.ShadowStreamWriter == nil { // first write
urspLen := len(rw.unsafeResponseStreamPrefix)
saltLen := len(rw.cipherConfig.PSK)
responseHeaderStart := urspLen + saltLen
responseHeaderEnd := responseHeaderStart + TCPRequestFixedLengthHeaderLength + saltLen
payloadBufStart := responseHeaderEnd + 16
bufferLen := payloadBufStart + payloadLen + 16
hb := make([]byte, bufferLen)
ursp := hb[:urspLen]
salt := hb[urspLen:responseHeaderStart]
responseHeader := hb[responseHeaderStart:responseHeaderEnd]
// Write unsafe response stream prefix.
copy(ursp, rw.unsafeResponseStreamPrefix)
// Random salt.
_, err := rand.Read(salt)
if err != nil {
return 0, err
}
// Write response header.
WriteTCPResponseHeader(responseHeader, rw.requestSalt, uint16(payloadLen))
// Create AEAD cipher.
shadowStreamCipher, err := rw.cipherConfig.ShadowStreamCipher(salt)
if err != nil {
return 0, err
}
// Create writer.
rw.ShadowStreamWriter = &ShadowStreamWriter{
writer: rw.rawRW,
ssc: shadowStreamCipher,
}
// Seal response header.
shadowStreamCipher.EncryptInPlace(responseHeader)
// Seal payload.
dst := hb[payloadBufStart:]
plaintext := b[payloadStart : payloadStart+payloadLen]
shadowStreamCipher.EncryptTo(dst, plaintext)
// Write out.
_, err = rw.rawRW.Write(hb)
if err != nil {
return 0, err
}
return payloadLen, nil
}
return rw.ShadowStreamWriter.WriteZeroCopy(b, payloadStart, payloadLen)
}
// CloseRead implements the ReadWriter CloseRead method.
func (rw *ShadowStreamServerReadWriter) CloseRead() error {
return rw.rawRW.CloseRead()
}
// CloseWrite implements the ReadWriter CloseWrite method.
func (rw *ShadowStreamServerReadWriter) CloseWrite() error {
return rw.rawRW.CloseWrite()
}
// Close implements the ReadWriter Close method.
func (rw *ShadowStreamServerReadWriter) Close() error {
return rw.rawRW.Close()
}
// ShadowStreamClientReadWriter implements Shadowsocks stream client.
type ShadowStreamClientReadWriter struct {
*ShadowStreamReader
*ShadowStreamWriter
rawRW zerocopy.DirectReadWriteCloser
readOnceOrFull func(io.Reader, []byte) (int, error)
cipherConfig *ClientCipherConfig
requestSalt []byte
unsafeResponseStreamPrefix []byte
}
// ReadZeroCopy implements the Reader ReadZeroCopy method.
func (rw *ShadowStreamClientReadWriter) ReadZeroCopy(b []byte, payloadBufStart, payloadBufLen int) (int, error) {
if rw.ShadowStreamReader == nil { // first read
urspLen := len(rw.unsafeResponseStreamPrefix)
saltLen := len(rw.cipherConfig.PSK)
fixedLengthHeaderStart := urspLen + saltLen
bufferLen := fixedLengthHeaderStart + TCPRequestFixedLengthHeaderLength + saltLen + 16
hb := make([]byte, bufferLen)
// Read response header.
n, err := rw.readOnceOrFull(rw.rawRW, hb)
if err != nil {
return 0, err
}
// Check unsafe response stream prefix.
ursp := hb[:urspLen]
if !bytes.Equal(ursp, rw.unsafeResponseStreamPrefix) {
return 0, &HeaderError[[]byte]{ErrUnsafeStreamPrefixMismatch, rw.unsafeResponseStreamPrefix, ursp}
}
// Derive key and create cipher.
salt := hb[urspLen:fixedLengthHeaderStart]
ciphertext := hb[fixedLengthHeaderStart:]
shadowStreamCipher, err := rw.cipherConfig.ShadowStreamCipher(salt)
if err != nil {
return 0, err
}
// Create reader.
rw.ShadowStreamReader = &ShadowStreamReader{
reader: rw.rawRW,
ssc: shadowStreamCipher,
}
// AEAD open.
plaintext, err := shadowStreamCipher.DecryptInPlace(ciphertext)
if err != nil {
return 0, err
}
// Parse response header.
n, err = ParseTCPResponseHeader(plaintext, rw.requestSalt)
if err != nil {
return 0, err
}
payloadBuf := b[payloadBufStart : payloadBufStart+n+16]
// Read payload chunk.
_, err = io.ReadFull(rw.rawRW, payloadBuf)
if err != nil {
return 0, err
}
// AEAD open.
_, err = shadowStreamCipher.DecryptInPlace(payloadBuf)
if err != nil {
return 0, err
}
return n, nil
}
return rw.ShadowStreamReader.ReadZeroCopy(b, payloadBufStart, payloadBufLen)
}
// CloseRead implements the ReadWriter CloseRead method.
func (rw *ShadowStreamClientReadWriter) CloseRead() error {
return rw.rawRW.CloseRead()
}
// CloseWrite implements the ReadWriter CloseWrite method.
func (rw *ShadowStreamClientReadWriter) CloseWrite() error {
return rw.rawRW.CloseWrite()
}
// Close implements the ReadWriter Close method.
func (rw *ShadowStreamClientReadWriter) Close() error {
return rw.rawRW.Close()
}
// ShadowStreamWriter wraps an io.WriteCloser and feeds an encrypted Shadowsocks stream to it.
//
// Wire format:
//
// +------------------------+---------------------------+
// | encrypted length chunk | encrypted payload chunk |
// +------------------------+---------------------------+
// | 2B length + 16B tag | variable length + 16B tag |
// +------------------------+---------------------------+
type ShadowStreamWriter struct {
writer io.WriteCloser
ssc *ShadowStreamCipher
}
// WriterInfo implements the Writer WriterInfo method.
func (w *ShadowStreamWriter) WriterInfo() zerocopy.WriterInfo {
return ShadowStreamWriterInfo
}
// WriteZeroCopy implements the Writer WriteZeroCopy method.
func (w *ShadowStreamWriter) WriteZeroCopy(b []byte, payloadStart, payloadLen int) (payloadWritten int, err error) {
overhead := w.ssc.Overhead()
lengthStart := payloadStart - overhead - 2
lengthBuf := b[lengthStart : lengthStart+2]
payloadBuf := b[payloadStart : payloadStart+payloadLen]
payloadTagEnd := payloadStart + payloadLen + overhead
chunksBuf := b[lengthStart:payloadTagEnd]
// Write length.
binary.BigEndian.PutUint16(lengthBuf, uint16(payloadLen))
// Seal length chunk.
w.ssc.EncryptInPlace(lengthBuf)
// Seal payload chunk.
w.ssc.EncryptInPlace(payloadBuf)
// Write to wrapped writer.
_, err = w.writer.Write(chunksBuf)
if err != nil {
return
}
payloadWritten = payloadLen
return
}
// ShadowStreamReader wraps an io.ReadCloser and reads from it as an encrypted Shadowsocks stream.
type ShadowStreamReader struct {
reader io.ReadCloser
ssc *ShadowStreamCipher
}
// ReaderInfo implements the Reader ReaderInfo method.
func (r *ShadowStreamReader) ReaderInfo() zerocopy.ReaderInfo {
return ShadowStreamReaderInfo
}
// ReadZeroCopy implements the Reader ReadZeroCopy method.
func (r *ShadowStreamReader) ReadZeroCopy(b []byte, payloadBufStart, payloadBufLen int) (payloadLen int, err error) {
overhead := r.ssc.Overhead()
sealedLengthChunkStart := payloadBufStart - overhead - 2
sealedLengthChunkBuf := b[sealedLengthChunkStart:payloadBufStart]
// Read sealed length chunk.
_, err = io.ReadFull(r.reader, sealedLengthChunkBuf)
if err != nil {
return
}
// Open sealed length chunk.
_, err = r.ssc.DecryptInPlace(sealedLengthChunkBuf)
if err != nil {
return
}
// Validate length.
payloadLen = int(binary.BigEndian.Uint16(sealedLengthChunkBuf))
if payloadLen == 0 {
err = ErrZeroLengthChunk
return
}
// Read sealed payload chunk.
sealedPayloadChunkBuf := b[payloadBufStart : payloadBufStart+payloadLen+overhead]
_, err = io.ReadFull(r.reader, sealedPayloadChunkBuf)
if err != nil {
payloadLen = 0
return
}
// Open sealed payload chunk.
_, err = r.ssc.DecryptInPlace(sealedPayloadChunkBuf)
if err != nil {
payloadLen = 0
}
return
}
// ShadowStreamCipher wraps an AEAD cipher and provides methods that transparently increments
// the nonce after each AEAD operation.
type ShadowStreamCipher struct {
aead cipher.AEAD
nonce []byte
}
// NewShadowStreamCipher wraps the given AEAD cipher into a new ShadowStreamCipher.
func NewShadowStreamCipher(aead cipher.AEAD) *ShadowStreamCipher {
return &ShadowStreamCipher{
aead: aead,
nonce: make([]byte, aead.NonceSize()),
}
}
// Overhead returns the tag size of the AEAD cipher.
func (c *ShadowStreamCipher) Overhead() int {
return c.aead.Overhead()
}
// EncryptInPlace encrypts and authenticates plaintext in-place.
func (c *ShadowStreamCipher) EncryptInPlace(plaintext []byte) (ciphertext []byte) {
ciphertext = c.aead.Seal(plaintext[:0], c.nonce, plaintext, nil)
increment(c.nonce)
return
}
// EncryptTo encrypts and authenticates the plaintext and saves the ciphertext to dst.
func (c *ShadowStreamCipher) EncryptTo(dst, plaintext []byte) (ciphertext []byte) {
ciphertext = c.aead.Seal(dst[:0], c.nonce, plaintext, nil)
increment(c.nonce)
return
}
// DecryptInplace decrypts and authenticates ciphertext in-place.
func (c *ShadowStreamCipher) DecryptInPlace(ciphertext []byte) (plaintext []byte, err error) {
plaintext, err = c.aead.Open(ciphertext[:0], c.nonce, ciphertext, nil)
if err == nil {
increment(c.nonce)
}
return
}
// DecryptTo decrypts and authenticates the ciphertext and saves the plaintext to dst.
func (c *ShadowStreamCipher) DecryptTo(dst, ciphertext []byte) (plaintext []byte, err error) {
plaintext, err = c.aead.Open(dst[:0], c.nonce, ciphertext, nil)
if err == nil {
increment(c.nonce)
}
return
}
// increment increments a little-endian unsigned integer b.
func increment(b []byte) {
for i := range b {
b[i]++
if b[i] != 0 {
return
}
}
}
// readOnceExpectFull reads exactly once from r into b and
// returns an error if the read fails to fill up b.
func readOnceExpectFull(r io.Reader, b []byte) (int, error) {
n, err := r.Read(b)
if err != nil {
return n, err
}
if n < len(b) {
return n, &HeaderError[int]{ErrFirstRead, len(b), n}
}
return n, nil
}
// readOnceOrFullFunc returns a function that either reads exactly once from r into b
// or reads until b is full, depending on the value of allowSegmentedFixedLengthHeader.
func readOnceOrFullFunc(allowSegmentedFixedLengthHeader bool) func(io.Reader, []byte) (int, error) {
if allowSegmentedFixedLengthHeader {
return io.ReadFull
}
return readOnceExpectFull
}