Debian Codegraph @

transports/obfs3/obfs3.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * Copyright (c) 2014, Yawning Angel <yawning at schwanenlied dot me>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 *
11 * * Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
19 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 // Package obfs3 provides an implementation of the Tor Project's obfs3
29 // obfuscation protocol.
30 package obfs3 // import "gitlab.com/yawning/obfs4.git/transports/obfs3"
31
32 import (
33 "bytes"
34 "crypto/aes"
35 "crypto/cipher"
36 "crypto/hmac"
37 "crypto/sha256"
38 "errors"
39 "io"
40 "net"
41 "time"
42
43 "git.torproject.org/pluggable-transports/goptlib.git"
44 "gitlab.com/yawning/obfs4.git/common/csrand"
45 "gitlab.com/yawning/obfs4.git/common/uniformdh"
46 "gitlab.com/yawning/obfs4.git/transports/base"
47 )
48
49 const (
50 transportName = "obfs3"
51
52 clientHandshakeTimeout = time.Duration(30) * time.Second
53 serverHandshakeTimeout = time.Duration(30) * time.Second
54
55 initiatorKdfString = "Initiator obfuscated data"
56 responderKdfString = "Responder obfuscated data"
57 initiatorMagicString = "Initiator magic"
58 responderMagicString = "Responder magic"
59 maxPadding = 8194
60 keyLen = 16
61 )
62
63 // Transport is the obfs3 implementation of the base.Transport interface.
64 type Transport struct{}
65
66 // Name returns the name of the obfs3 transport protocol.
67 func (t *Transport) Name() string {
68 return transportName
69 }
70
71 // ClientFactory returns a new obfs3ClientFactory instance.
72 func (t *Transport) ClientFactory(stateDir string) (base.ClientFactory, error) {
73 cf := &obfs3ClientFactory{transport: t}
74 return cf, nil
75 }
76
77 // ServerFactory returns a new obfs3ServerFactory instance.
78 func (t *Transport) ServerFactory(stateDir string, args *pt.Args) (base.ServerFactory, error) {
79 sf := &obfs3ServerFactory{transport: t}
80 return sf, nil
81 }
82
83 type obfs3ClientFactory struct {
84 transport base.Transport
85 }
86
87 func (cf *obfs3ClientFactory) Transport() base.Transport {
88 return cf.transport
89 }
90
91 func (cf *obfs3ClientFactory) ParseArgs(args *pt.Args) (interface{}, error) {
92 return nil, nil
93 }
94
95 func (cf *obfs3ClientFactory) Dial(network, addr string, dialFn base.DialFunc, args interface{}) (net.Conn, error) {
96 conn, err := dialFn(network, addr)
97 if err != nil {
98 return nil, err
99 }
100 dialConn := conn
101 if conn, err = newObfs3ClientConn(conn); err != nil {
102 dialConn.Close()
103 return nil, err
104 }
105 return conn, nil
106 }
107
108 type obfs3ServerFactory struct {
109 transport base.Transport
110 }
111
112 func (sf *obfs3ServerFactory) Transport() base.Transport {
113 return sf.transport
114 }
115
116 func (sf *obfs3ServerFactory) Args() *pt.Args {
117 return nil
118 }
119
120 func (sf *obfs3ServerFactory) WrapConn(conn net.Conn) (net.Conn, error) {
121 return newObfs3ServerConn(conn)
122 }
123
124 type obfs3Conn struct {
125 net.Conn
126
127 isInitiator bool
128 rxMagic []byte
129 txMagic []byte
130 rxBuf *bytes.Buffer
131
132 rx *cipher.StreamReader
133 tx *cipher.StreamWriter
134 }
135
136 func newObfs3ClientConn(conn net.Conn) (c *obfs3Conn, err error) {
137 // Initialize a client connection, and start the handshake timeout.
138 c = &obfs3Conn{conn, true, nil, nil, new(bytes.Buffer), nil, nil}
139 deadline := time.Now().Add(clientHandshakeTimeout)
140 if err = c.SetDeadline(deadline); err != nil {
141 return nil, err
142 }
143
144 // Handshake.
145 if err = c.handshake(); err != nil {
146 return nil, err
147 }
148
149 // Disarm the handshake timer.
150 if err = c.SetDeadline(time.Time{}); err != nil {
151 return nil, err
152 }
153
154 return
155 }
156
157 func newObfs3ServerConn(conn net.Conn) (c *obfs3Conn, err error) {
158 // Initialize a server connection, and start the handshake timeout.
159 c = &obfs3Conn{conn, false, nil, nil, new(bytes.Buffer), nil, nil}
160 deadline := time.Now().Add(serverHandshakeTimeout)
161 if err = c.SetDeadline(deadline); err != nil {
162 return nil, err
163 }
164
165 // Handshake.
166 if err = c.handshake(); err != nil {
167 return nil, err
168 }
169
170 // Disarm the handshake timer.
171 if err = c.SetDeadline(time.Time{}); err != nil {
172 return nil, err
173 }
174
175 return
176 }
177
178 func (conn *obfs3Conn) handshake() error {
179 // The party who opens the connection is the 'initiator'; the one who
180 // accepts it is the 'responder'. Each begins by generating a
181 // UniformDH keypair, and a random number PADLEN in [0, MAX_PADDING/2].
182 // Both parties then send:
183 //
184 // PUB_KEY | WR(PADLEN)
185 privateKey, err := uniformdh.GenerateKey(csrand.Reader)
186 if err != nil {
187 return err
188 }
189 padLen := csrand.IntRange(0, maxPadding/2)
190 blob := make([]byte, uniformdh.Size+padLen)
191 publicKey, err := privateKey.PublicKey.Bytes()
192 if err != nil {
193 return err
194 }
195 copy(blob[0:], publicKey)
196 if err := csrand.Bytes(blob[uniformdh.Size:]); err != nil {
197 return err
198 }
199 if _, err := conn.Conn.Write(blob); err != nil {
200 return err
201 }
202
203 // Read the public key from the peer.
204 rawPeerPublicKey := make([]byte, uniformdh.Size)
205 if _, err := io.ReadFull(conn.Conn, rawPeerPublicKey); err != nil {
206 return err
207 }
208 var peerPublicKey uniformdh.PublicKey
209 if err := peerPublicKey.SetBytes(rawPeerPublicKey); err != nil {
210 return err
211 }
212
213 // After retrieving the public key of the other end, each party
214 // completes the DH key exchange and generates a shared-secret for the
215 // session (named SHARED_SECRET).
216 sharedSecret, err := uniformdh.Handshake(privateKey, &peerPublicKey)
217 if err != nil {
218 return err
219 }
220 if err := conn.kdf(sharedSecret); err != nil {
221 return err
222 }
223
224 return nil
225 }
226
227 func (conn *obfs3Conn) kdf(sharedSecret []byte) error {
228 // Using that shared-secret each party derives its encryption keys as
229 // follows:
230 //
231 // INIT_SECRET = HMAC(SHARED_SECRET, "Initiator obfuscated data")
232 // RESP_SECRET = HMAC(SHARED_SECRET, "Responder obfuscated data")
233 // INIT_KEY = INIT_SECRET[:KEYLEN]
234 // INIT_COUNTER = INIT_SECRET[KEYLEN:]
235 // RESP_KEY = RESP_SECRET[:KEYLEN]
236 // RESP_COUNTER = RESP_SECRET[KEYLEN:]
237 initHmac := hmac.New(sha256.New, sharedSecret)
238 _, _ = initHmac.Write([]byte(initiatorKdfString))
239 initSecret := initHmac.Sum(nil)
240 initHmac.Reset()
241 _, _ = initHmac.Write([]byte(initiatorMagicString))
242 initMagic := initHmac.Sum(nil)
243
244 respHmac := hmac.New(sha256.New, sharedSecret)
245 _, _ = respHmac.Write([]byte(responderKdfString))
246 respSecret := respHmac.Sum(nil)
247 respHmac.Reset()
248 _, _ = respHmac.Write([]byte(responderMagicString))
249 respMagic := respHmac.Sum(nil)
250
251 // The INIT_KEY value keys a block cipher (in CTR mode) used to
252 // encrypt values from initiator to responder thereafter. The counter
253 // mode's initial counter value is INIT_COUNTER. The RESP_KEY value
254 // keys a block cipher (in CTR mode) used to encrypt values from
255 // responder to initiator thereafter. That counter mode's initial
256 // counter value is RESP_COUNTER.
257 //
258 // Note: To have this be the last place where the shared secret is used,
259 // also generate the magic value to send/scan for here.
260 initBlock, err := aes.NewCipher(initSecret[:keyLen])
261 if err != nil {
262 return err
263 }
264 initStream := cipher.NewCTR(initBlock, initSecret[keyLen:])
265
266 respBlock, err := aes.NewCipher(respSecret[:keyLen])
267 if err != nil {
268 return err
269 }
270 respStream := cipher.NewCTR(respBlock, respSecret[keyLen:])
271
272 if conn.isInitiator {
273 conn.tx = &cipher.StreamWriter{S: initStream, W: conn.Conn}
274 conn.rx = &cipher.StreamReader{S: respStream, R: conn.rxBuf}
275 conn.txMagic = initMagic
276 conn.rxMagic = respMagic
277 } else {
278 conn.tx = &cipher.StreamWriter{S: respStream, W: conn.Conn}
279 conn.rx = &cipher.StreamReader{S: initStream, R: conn.rxBuf}
280 conn.txMagic = respMagic
281 conn.rxMagic = initMagic
282 }
283
284 return nil
285 }
286
287 func (conn *obfs3Conn) findPeerMagic() error {
288 var hsBuf [maxPadding + sha256.Size]byte
289 for {
290 n, err := conn.Conn.Read(hsBuf[:])
291 if err != nil {
292 // Yes, Read can return partial data and an error, but continuing
293 // past that is nonsensical.
294 return err
295 }
296 conn.rxBuf.Write(hsBuf[:n])
297
298 pos := bytes.Index(conn.rxBuf.Bytes(), conn.rxMagic)
299 if pos == -1 {
300 if conn.rxBuf.Len() >= maxPadding+sha256.Size {
301 return errors.New("failed to find peer magic value")
302 }
303 continue
304 } else if pos > maxPadding {
305 return errors.New("peer sent too much pre-magic-padding")
306 }
307
308 // Discard the padding/MAC.
309 pos += len(conn.rxMagic)
310 _ = conn.rxBuf.Next(pos)
311
312 return nil
313 }
314 }
315
316 func (conn *obfs3Conn) Read(b []byte) (n int, err error) {
317 // If this is the first time we read data post handshake, scan for the
318 // magic value.
319 if conn.rxMagic != nil {
320 if err = conn.findPeerMagic(); err != nil {
321 conn.Close()
322 return
323 }
324 conn.rxMagic = nil
325 }
326
327 // If the handshake receive buffer is still present...
328 if conn.rxBuf != nil {
329 // And it is empty...
330 if conn.rxBuf.Len() == 0 {
331 // There is no more trailing data left from the handshake process,
332 // so rewire the cipher.StreamReader to pull data from the network
333 // instead of the temporary receive buffer.
334 conn.rx.R = conn.Conn
335 conn.rxBuf = nil
336 }
337 }
338
339 return conn.rx.Read(b)
340 }
341
342 func (conn *obfs3Conn) Write(b []byte) (n int, err error) {
343 // If this is the first time we write data post handshake, send the
344 // padding/magic value.
345 if conn.txMagic != nil {
346 padLen := csrand.IntRange(0, maxPadding/2)
347 blob := make([]byte, padLen+len(conn.txMagic))
348 if err = csrand.Bytes(blob[:padLen]); err != nil {
349 conn.Close()
350 return
351 }
352 copy(blob[padLen:], conn.txMagic)
353 if _, err = conn.Conn.Write(blob); err != nil {
354 conn.Close()
355 return
356 }
357 conn.txMagic = nil
358 }
359
360 return conn.tx.Write(b)
361 }
362
363 var _ base.ClientFactory = (*obfs3ClientFactory)(nil)
364 var _ base.ServerFactory = (*obfs3ServerFactory)(nil)
365 var _ base.Transport = (*Transport)(nil)
366 var _ net.Conn = (*obfs3Conn)(nil)