-
Notifications
You must be signed in to change notification settings - Fork 258
/
obfuscator.go
409 lines (333 loc) · 11.1 KB
/
obfuscator.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
403
404
405
406
407
408
409
/*
* Copyright (c) 2018, Psiphon Inc.
* All rights reserved.
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package quic
import (
"crypto/sha256"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/Psiphon-Labs/goarista/monotime"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/hkdf"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
"github.com/Yawning/chacha20"
)
const (
MAX_QUIC_IPV4_PACKET_SIZE = 1252
MAX_QUIC_IPV6_PACKET_SIZE = 1232
MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE = 1372
MAX_OBFUSCATED_QUIC_IPV6_PACKET_SIZE = 1352
MAX_PADDING = 64
NONCE_SIZE = 12
RANDOM_STREAM_LIMIT = 1<<38 - 64
)
// ObfuscatedPacketConn wraps a QUIC net.PacketConn with an obfuscation layer
// that obscures QUIC packets, adding random padding and producing uniformly
// random payload.
//
// The crypto performed by ObfuscatedPacketConn is purely for obfuscation to
// frusctrate wire-speed DPI and does not add privacy/security. The small
// nonce space and single key per server is not cryptographically secure.
//
// A server-side ObfuscatedPacketConn performs simple QUIC DPI to distinguish
// between obfuscated and non-obfsucated peer flows and responds accordingly.
//
// The header and padding added by ObfuscatedPacketConn on top of the QUIC
// payload will increase UDP packets beyond the QUIC max of 1280 bytes,
// introducing some risk of fragmentation and/or dropped packets.
type ObfuscatedPacketConn struct {
net.PacketConn
isServer bool
isClosed int32
runWaitGroup *sync.WaitGroup
stopBroadcast chan struct{}
obfuscationKey [32]byte
peerModesMutex sync.Mutex
peerModes map[string]*peerMode
noncePRNG *prng.PRNG
paddingPRNG *prng.PRNG
}
type peerMode struct {
isObfuscated bool
lastPacketTime monotime.Time
}
func (p *peerMode) isStale() bool {
return monotime.Since(p.lastPacketTime) >= SERVER_IDLE_TIMEOUT
}
// NewObfuscatedPacketConn creates a new ObfuscatedPacketConn.
func NewObfuscatedPacketConn(
conn net.PacketConn,
isServer bool,
obfuscationKey string,
paddingSeed *prng.Seed) (*ObfuscatedPacketConn, error) {
// There is no replay of obfuscation "encryption", just padding.
nonceSeed, err := prng.NewSeed()
if err != nil {
return nil, common.ContextError(err)
}
packetConn := &ObfuscatedPacketConn{
PacketConn: conn,
isServer: isServer,
peerModes: make(map[string]*peerMode),
noncePRNG: prng.NewPRNGWithSeed(nonceSeed),
paddingPRNG: prng.NewPRNGWithSeed(paddingSeed),
}
secret := []byte(obfuscationKey)
salt := []byte("quic-obfuscation-key")
_, err = io.ReadFull(
hkdf.New(sha256.New, secret, salt, nil), packetConn.obfuscationKey[:])
if err != nil {
return nil, common.ContextError(err)
}
if isServer {
packetConn.runWaitGroup = new(sync.WaitGroup)
packetConn.stopBroadcast = make(chan struct{}, 1)
// Reap stale peer mode information to reclaim memory.
packetConn.runWaitGroup.Add(1)
go func() {
defer packetConn.runWaitGroup.Done()
ticker := time.NewTicker(SERVER_IDLE_TIMEOUT / 2)
defer ticker.Stop()
for {
select {
case <-ticker.C:
packetConn.peerModesMutex.Lock()
for address, mode := range packetConn.peerModes {
if mode.isStale() {
delete(packetConn.peerModes, address)
}
}
packetConn.peerModesMutex.Unlock()
case <-packetConn.stopBroadcast:
return
}
}
}()
}
return packetConn, nil
}
func (conn *ObfuscatedPacketConn) Close() error {
// Ensure close channel only called once.
if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
return nil
}
if conn.isServer {
close(conn.stopBroadcast)
conn.runWaitGroup.Wait()
}
return conn.PacketConn.Close()
}
type temporaryNetError struct {
err error
}
func newTemporaryNetError(err error) *temporaryNetError {
return &temporaryNetError{err: err}
}
func (e *temporaryNetError) Timeout() bool {
return false
}
func (e *temporaryNetError) Temporary() bool {
return true
}
func (e *temporaryNetError) Error() string {
return e.err.Error()
}
func (conn *ObfuscatedPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
n, addr, err := conn.PacketConn.ReadFrom(p)
// Data is processed even when err != nil, as ReadFrom may return both
// a packet and an error, such as io.EOF.
// See: https://golang.org/pkg/net/#PacketConn.
if n > 0 {
isObfuscated := true
if conn.isServer {
// The server handles both plain and obfuscated QUIC packets.
// isQUIC performs DPI to determine whether the packet appears to
// be QUIC, in which case deobfuscation is not performed. Not all
// plain QUIC packets will pass the DPI test, but the initial
// packet(s) in a flow are expected to match; so the server
// records a peer "mode", referenced by peer address to know when
// to skip deobfuscation for later packets.
//
// It's possible for clients to redial QUIC connections,
// transitioning from obfuscated to plain, using the same source
// address (IP and port). This is more likely when many clients
// are behind NAT. If a packet appears to be QUIC, this will reset
// any existing peer "mode" to plain. The obfuscator checks that
// its obfuscated packets don't pass the QUIC DPI test.
//
// TODO: delete peerMode when a packet is a client connection
// termination QUIC packet? Will reclaim peerMode memory faster
// than relying on reaper.
isQUIC := isQUIC(p[:n])
// Without addr, the mode cannot be determined.
if addr == nil {
return n, addr, newTemporaryNetError(common.ContextError(
fmt.Errorf("missing addr")))
}
conn.peerModesMutex.Lock()
address := addr.String()
mode, ok := conn.peerModes[address]
if !ok {
mode = &peerMode{isObfuscated: !isQUIC}
conn.peerModes[address] = mode
} else if mode.isStale() {
mode.isObfuscated = !isQUIC
} else if mode.isObfuscated && isQUIC {
mode.isObfuscated = false
}
isObfuscated = mode.isObfuscated
mode.lastPacketTime = monotime.Now()
conn.peerModesMutex.Unlock()
}
if isObfuscated {
// We can use p as a scratch buffer for deobfuscation, and this
// avoids allocting a buffer.
if n < (NONCE_SIZE + 1) {
return n, addr, newTemporaryNetError(common.ContextError(
fmt.Errorf("unexpected obfuscated QUIC packet length: %d", n)))
}
cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], p[0:NONCE_SIZE])
if err != nil {
return n, addr, common.ContextError(err)
}
cipher.XORKeyStream(p[NONCE_SIZE:], p[NONCE_SIZE:])
paddingLen := int(p[NONCE_SIZE])
if paddingLen > MAX_PADDING || paddingLen > n-(NONCE_SIZE+1) {
return n, addr, newTemporaryNetError(common.ContextError(
fmt.Errorf("unexpected padding length: %d, %d", paddingLen, n)))
}
n -= (NONCE_SIZE + 1) + paddingLen
copy(p[0:n], p[(NONCE_SIZE+1)+paddingLen:n+(NONCE_SIZE+1)+paddingLen])
}
}
// Do not wrap any err returned by conn.PacketConn.ReadFrom.
return n, addr, err
}
type obfuscatorBuffer struct {
buffer [MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE]byte
}
var obfuscatorBufferPool = &sync.Pool{
New: func() interface{} {
return new(obfuscatorBuffer)
},
}
func getMaxPacketSizes(addr net.Addr) (int, int) {
if udpAddr, ok := addr.(*net.UDPAddr); ok && udpAddr.IP.To4() == nil {
return MAX_QUIC_IPV6_PACKET_SIZE, MAX_OBFUSCATED_QUIC_IPV6_PACKET_SIZE
}
return MAX_QUIC_IPV4_PACKET_SIZE, MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE
}
func (conn *ObfuscatedPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
n := len(p)
isObfuscated := true
if conn.isServer {
conn.peerModesMutex.Lock()
address := addr.String()
mode, ok := conn.peerModes[address]
isObfuscated = ok && mode.isObfuscated
conn.peerModesMutex.Unlock()
}
if isObfuscated {
maxQUICPacketSize, maxObfuscatedPacketSize := getMaxPacketSizes(addr)
if n > maxQUICPacketSize {
return 0, newTemporaryNetError(common.ContextError(
fmt.Errorf("unexpected QUIC packet length: %d", n)))
}
// Note: escape analysis showed a local array escaping to the heap,
// so use a buffer pool instead to avoid heap allocation per packet.
b := obfuscatorBufferPool.Get().(*obfuscatorBuffer)
buffer := b.buffer[:]
defer obfuscatorBufferPool.Put(b)
for {
// Note: this zero-memory pattern is compiler optimized:
// https://golang.org/cl/137880043
for i := range buffer {
buffer[i] = 0
}
nonce := buffer[0:NONCE_SIZE]
conn.noncePRNG.Read(nonce)
// Obfuscated QUIC padding results in packets that exceed the
// QUIC max packet size of 1280.
maxPaddingLen := maxObfuscatedPacketSize - (n + (NONCE_SIZE + 1))
if maxPaddingLen < 0 {
maxPaddingLen = 0
}
if maxPaddingLen > MAX_PADDING {
maxPaddingLen = MAX_PADDING
}
paddingLen := conn.paddingPRNG.Intn(maxPaddingLen + 1)
buffer[NONCE_SIZE] = uint8(paddingLen)
padding := buffer[(NONCE_SIZE + 1) : (NONCE_SIZE+1)+paddingLen]
conn.paddingPRNG.Read(padding)
copy(buffer[(NONCE_SIZE+1)+paddingLen:], p)
dataLen := (NONCE_SIZE + 1) + paddingLen + n
cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], nonce)
if err != nil {
return 0, common.ContextError(err)
}
packet := buffer[NONCE_SIZE:dataLen]
cipher.XORKeyStream(packet, packet)
p = buffer[:dataLen]
// Don't use obfuscation that looks like QUIC, or the
// peer will not treat this packet as obfuscated.
if !isQUIC(p) {
break
}
}
}
_, err := conn.PacketConn.WriteTo(p, addr)
// Do not wrap any err returned by conn.PacketConn.WriteTo.
return n, err
}
func isQUIC(buffer []byte) bool {
// As this function is called for every packet, it needs to be fast.
//
// In all currently supported versions, the first client packet contains
// the "CHLO" tag at one of the following offsets. The offset can vary for
// a single version.
//
// Note that v44 does not include the "QUIC version" header field in its
// first client packet.
//
// As QUIC header parsing is complex, with many cases, we are not
// presently doing that, although this might improve accuracy as we should
// be able to identify the precise offset of "CHLO" based on header
// values.
if (len(buffer) >= 33 &&
buffer[29] == 'C' &&
buffer[30] == 'H' &&
buffer[31] == 'L' &&
buffer[32] == 'O') ||
(len(buffer) >= 35 &&
buffer[31] == 'C' &&
buffer[32] == 'H' &&
buffer[33] == 'L' &&
buffer[34] == 'O') ||
(len(buffer) >= 38 &&
buffer[34] == 'C' &&
buffer[35] == 'H' &&
buffer[36] == 'L' &&
buffer[37] == 'O') {
return true
}
return false
}