summaryrefslogtreecommitdiff
path: root/obfs4.go
blob: cd6f75da5ddbd7da93bf60589905a52473f159e4 (plain)
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*
 * Copyright (c) 2014, Yawning Angel <yawning at torproject dot org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

// Package obfs4 implements the obfs4 protocol.
package obfs4

import (
	"bytes"
	"fmt"
	"net"
	"syscall"
	"time"

	"github.com/yawning/obfs4/framing"
	"github.com/yawning/obfs4/ntor"
)

const (
	headerLength      = framing.FrameOverhead + packetOverhead
	defaultReadSize   = framing.MaximumSegmentLength
	connectionTimeout = time.Duration(15) * time.Second

	minCloseThreshold = 0
	maxCloseThreshold = framing.MaximumSegmentLength * 5
	minCloseInterval  = 0
	maxCloseInterval  = 60
)

// Obfs4Conn is the implementation of the net.Conn interface for obfs4
// connections.
type Obfs4Conn struct {
	conn net.Conn

	probDist *wDist

	encoder *framing.Encoder
	decoder *framing.Decoder

	receiveBuffer        bytes.Buffer
	receiveDecodedBuffer bytes.Buffer

	isOk     bool
	isServer bool

	// Server side state.
	listener *Obfs4Listener
}

func (c *Obfs4Conn) calcPadLen(burstLen int) int {
	tailLen := burstLen % framing.MaximumSegmentLength
	toPadTo := c.probDist.sample()

	ret := 0
	if toPadTo >= tailLen {
		ret = toPadTo - tailLen
	} else {
		ret = (framing.MaximumSegmentLength - tailLen) + toPadTo
	}

	return ret
}

func (c *Obfs4Conn) closeAfterDelay() {
	// I-it's not like I w-wanna handshake with you or anything.  B-b-baka!
	defer c.conn.Close()

	delaySecs := randRange(minCloseInterval, maxCloseInterval)
	toDiscard := randRange(minCloseThreshold, maxCloseThreshold)

	delay := time.Duration(delaySecs) * time.Second
	err := c.conn.SetReadDeadline(time.Now().Add(delay))
	if err != nil {
		return
	}

	// Consume and discard data on this connection until either the specified
	// interval passes or a certain size has been reached.
	discarded := 0
	buf := make([]byte, defaultReadSize)
	for discarded < int(toDiscard) {
		n, err := c.conn.Read(buf)
		if err != nil {
			return
		}
		discarded += n
	}
}

func (c *Obfs4Conn) clientHandshake(nodeID *ntor.NodeID, publicKey *ntor.PublicKey) error {
	if c.isServer {
		panic(fmt.Sprintf("BUG: clientHandshake() called for server connection"))
	}

	// Generate/send the client handshake.
	hs, err := newClientHandshake(nodeID, publicKey)
	if err != nil {
		return err
	}
	blob, err := hs.generateHandshake()
	if err != nil {
		return err
	}

	err = c.conn.SetDeadline(time.Now().Add(connectionTimeout * 2))
	if err != nil {
		return err
	}

	_, err = c.conn.Write(blob)
	if err != nil {
		return err
	}

	// Consume the server handshake.
	hsBuf := make([]byte, serverMaxHandshakeLength)
	for {
		n, err := c.conn.Read(hsBuf)
		if err != nil {
			return err
		}
		c.receiveBuffer.Write(hsBuf[:n])

		n, seed, err := hs.parseServerHandshake(c.receiveBuffer.Bytes())
		if err == ErrMarkNotFoundYet {
			continue
		} else if err != nil {
			return err
		}
		_ = c.receiveBuffer.Next(n)

		err = c.conn.SetDeadline(time.Time{})
		if err != nil {
			return err
		}

		// Use the derived key material to intialize the link crypto.
		okm := ntor.Kdf(seed, framing.KeyLength*2)
		c.encoder = framing.NewEncoder(okm[:framing.KeyLength])
		c.decoder = framing.NewDecoder(okm[framing.KeyLength:])

		c.isOk = true

		return nil
	}
}

func (c *Obfs4Conn) serverHandshake(nodeID *ntor.NodeID, keypair *ntor.Keypair) error {
	if !c.isServer {
		panic(fmt.Sprintf("BUG: serverHandshake() called for client connection"))
	}

	hs := newServerHandshake(nodeID, keypair)
	err := c.conn.SetDeadline(time.Now().Add(connectionTimeout))
	if err != nil {
		return err
	}

	// Consume the client handshake.
	hsBuf := make([]byte, clientMaxHandshakeLength)
	for {
		n, err := c.conn.Read(hsBuf)
		if err != nil {
			return err
		}
		c.receiveBuffer.Write(hsBuf[:n])

		seed, err := hs.parseClientHandshake(c.receiveBuffer.Bytes())
		if err == ErrMarkNotFoundYet {
			continue
		} else if err != nil {
			return err
		}
		c.receiveBuffer.Reset()

		// Use the derived key material to intialize the link crypto.
		okm := ntor.Kdf(seed, framing.KeyLength*2)
		c.encoder = framing.NewEncoder(okm[framing.KeyLength:])
		c.decoder = framing.NewDecoder(okm[:framing.KeyLength])

		break
	}

	// Generate/send the response.
	blob, err := hs.generateHandshake()
	if err != nil {
		return err
	}
	_, err = c.conn.Write(blob)
	if err != nil {
		return err
	}

	err = c.conn.SetDeadline(time.Time{})
	if err != nil {
		return err
	}

	c.isOk = true

	// TODO: Generate/send the PRNG seed.

	return nil
}

func (c *Obfs4Conn) ServerHandshake() error {
	// Handshakes when already established are a no-op.
	if c.isOk {
		return nil
	}

	// Clients handshake as part of Dial.
	if !c.isServer {
		panic(fmt.Sprintf("BUG: ServerHandshake() called for client connection"))
	}

	// Regardless of what happens, don't need the listener past returning from
	// this routine.
	defer func() {
		c.listener = nil
	}()

	// Complete the handshake.
	err := c.serverHandshake(c.listener.nodeID, c.listener.keyPair)
	if err != nil {
		c.closeAfterDelay()
	}

	return err
}

func (c *Obfs4Conn) Read(b []byte) (int, error) {
	if !c.isOk {
		return 0, syscall.EINVAL
	}

	if c.receiveDecodedBuffer.Len() > 0 {
		n, err := c.receiveDecodedBuffer.Read(b)
		return n, err
	}

	// Consume and decode frames off the network.
	buf := make([]byte, defaultReadSize)
	for c.receiveDecodedBuffer.Len() == 0 {
		n, err := c.conn.Read(buf)
		if err != nil {
			return 0, err
		}
		c.receiveBuffer.Write(buf[:n])

		// Decode the data just read.
		for c.receiveBuffer.Len() > 0 {
			_, frame, err := c.decoder.Decode(&c.receiveBuffer)
			if err == framing.ErrAgain {
				break
			} else if err != nil {
				// Any other frame decoder errors are fatal.
				c.isOk = false
				return 0, err
			}

			// Decode the packet, if there is payload, it will be placed in
			// receiveDecodedBuffer automatically.
			err = c.decodePacket(frame)
			if err != nil {
				// All packet decoder errors are fatal.
				c.isOk = false
				return 0, err
			}
		}
	}

	n, err := c.receiveDecodedBuffer.Read(b)
	return n, err
}

func (c *Obfs4Conn) Write(b []byte) (int, error) {
	chopBuf := bytes.NewBuffer(b)
	buf := make([]byte, maxPacketPayloadLength)
	nSent := 0
	var frameBuf bytes.Buffer

	for chopBuf.Len() > 0 {
		// Send maximum sized frames.
		n, err := chopBuf.Read(buf)
		if err != nil {
			c.isOk = false
			return 0, err
		} else if n == 0 {
			panic(fmt.Sprintf("BUG: Write(), chopping length was 0"))
		}
		nSent += n

		_, frame, err := c.makeAndEncryptPacket(packetTypePayload, buf[:n], 0)
		if err != nil {
			c.isOk = false
			return 0, err
		}

		frameBuf.Write(frame)
	}

	// Insert random padding.  In theory it's possible to inline padding for
	// certain framesizes into the last AEAD packet, but always sending 1 or 2
	// padding frames is considerably easier.
	padLen := c.calcPadLen(frameBuf.Len())
	if padLen > 0 {
		if padLen > headerLength {
			_, frame, err := c.makeAndEncryptPacket(packetTypePayload, []byte{},
				uint16(padLen-headerLength))
			if err != nil {
				c.isOk = false
				return 0, err
			}
			frameBuf.Write(frame)
		} else {
			_, frame, err := c.makeAndEncryptPacket(packetTypePayload, []byte{},
				maxPacketPayloadLength)
			if err != nil {
				c.isOk = false
				return 0, err
			}
			frameBuf.Write(frame)

			_, frame, err = c.makeAndEncryptPacket(packetTypePayload, []byte{},
				uint16(padLen))
			if err != nil {
				c.isOk = false
				return 0, err
			}
			frameBuf.Write(frame)
		}
	}

	// Send the frame(s).
	_, err := c.conn.Write(frameBuf.Bytes())
	if err != nil {
		// Partial writes are fatal because the frame encoder state is advanced
		// at this point.  It's possible to keep frameBuf around, but fuck it.
		// Someone that wants write timeouts can change this.
		c.isOk = false
		return 0, err
	}

	return nSent, nil
}

func (c *Obfs4Conn) Close() error {
	if c.conn == nil {
		return syscall.EINVAL
	}

	c.isOk = false

	return c.conn.Close()
}

func (c *Obfs4Conn) LocalAddr() net.Addr {
	if !c.isOk {
		return nil
	}

	return c.conn.LocalAddr()
}

func (c *Obfs4Conn) RemoteAddr() net.Addr {
	if !c.isOk {
		return nil
	}

	return c.conn.RemoteAddr()
}

func (c *Obfs4Conn) SetDeadline(t time.Time) error {
	return syscall.ENOTSUP
}

func (c *Obfs4Conn) SetReadDeadline(t time.Time) error {
	if !c.isOk {
		return syscall.EINVAL
	}

	return c.conn.SetReadDeadline(t)
}

func (c *Obfs4Conn) SetWriteDeadline(t time.Time) error {
	return syscall.ENOTSUP
}

func Dial(network, address, nodeID, publicKey string) (net.Conn, error) {
	// Decode the node_id/public_key.
	pub, err := ntor.PublicKeyFromBase64(publicKey)
	if err != nil {
		return nil, err
	}
	id, err := ntor.NodeIDFromBase64(nodeID)
	if err != nil {
		return nil, err
	}

	// Connect to the peer.
	c := new(Obfs4Conn)
	c.probDist, err = newWDist(nil, 0, framing.MaximumSegmentLength)
	if err != nil {
		return nil, err
	}
	c.conn, err = net.Dial(network, address)
	if err != nil {
		return nil, err
	}

	// Handshake.
	err = c.clientHandshake(id, pub)
	if err != nil {
		c.conn.Close()
		return nil, err
	}

	return c, nil
}

// Obfs4Listener a obfs4 network listener.  Servers should use variables of
// type Listener instead of assuming obfs4.
type Obfs4Listener struct {
	listener net.Listener

	keyPair *ntor.Keypair
	nodeID  *ntor.NodeID
}

func (l *Obfs4Listener) Accept() (net.Conn, error) {
	// Accept a connection.
	c, err := l.listener.Accept()
	if err != nil {
		return nil, err
	}

	// Allocate the obfs4 connection state.
	cObfs := new(Obfs4Conn)
	cObfs.conn = c
	cObfs.isServer = true
	cObfs.listener = l
	cObfs.probDist, err = newWDist(nil, 0, framing.MaximumSegmentLength)
	if err != nil {
		c.Close()
		return nil, err
	}

	return cObfs, nil
}

func (l *Obfs4Listener) Close() error {
	return l.listener.Close()
}

func (l *Obfs4Listener) Addr() net.Addr {
	return l.listener.Addr()
}

func (l *Obfs4Listener) PublicKey() string {
	if l.keyPair == nil {
		return ""
	}
	return l.keyPair.Public().Base64()
}

func Listen(network, laddr, nodeID, privateKey string) (net.Listener, error) {
	var err error

	// Decode node_id/private_key.
	l := new(Obfs4Listener)
	l.keyPair, err = ntor.KeypairFromBase64(privateKey)
	if err != nil {
		return nil, err
	}
	l.nodeID, err = ntor.NodeIDFromBase64(nodeID)
	if err != nil {
		return nil, err
	}

	// Start up the listener.
	l.listener, err = net.Listen(network, laddr)
	if err != nil {
		return nil, err
	}

	return l, nil
}