| 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 obfs4 provides an implementation of the Tor Project's obfs4 |
| 29 |
// obfuscation protocol. |
| 30 |
package obfs4 // import "gitlab.com/yawning/obfs4.git/transports/obfs4" |
| 31 |
|
| 32 |
import ( |
| 33 |
"bytes" |
| 34 |
"crypto/sha256" |
| 35 |
"flag" |
| 36 |
"fmt" |
| 37 |
"io" |
| 38 |
"io/ioutil" |
| 39 |
"math/rand" |
| 40 |
"net" |
| 41 |
"strconv" |
| 42 |
"syscall" |
| 43 |
"time" |
| 44 |
|
| 45 |
"git.torproject.org/pluggable-transports/goptlib.git" |
| 46 |
"gitlab.com/yawning/obfs4.git/common/drbg" |
| 47 |
"gitlab.com/yawning/obfs4.git/common/ntor" |
| 48 |
"gitlab.com/yawning/obfs4.git/common/probdist" |
| 49 |
"gitlab.com/yawning/obfs4.git/common/replayfilter" |
| 50 |
"gitlab.com/yawning/obfs4.git/transports/base" |
| 51 |
"gitlab.com/yawning/obfs4.git/transports/obfs4/framing" |
| 52 |
) |
| 53 |
|
| 54 |
const ( |
| 55 |
transportName = "obfs4" |
| 56 |
|
| 57 |
nodeIDArg = "node-id" |
| 58 |
publicKeyArg = "public-key" |
| 59 |
privateKeyArg = "private-key" |
| 60 |
seedArg = "drbg-seed" |
| 61 |
iatArg = "iat-mode" |
| 62 |
certArg = "cert" |
| 63 |
|
| 64 |
biasCmdArg = "obfs4-distBias" |
| 65 |
|
| 66 |
seedLength = drbg.SeedLength |
| 67 |
headerLength = framing.FrameOverhead + packetOverhead |
| 68 |
clientHandshakeTimeout = time.Duration(60) * time.Second |
| 69 |
serverHandshakeTimeout = time.Duration(30) * time.Second |
| 70 |
replayTTL = time.Duration(3) * time.Hour |
| 71 |
|
| 72 |
maxIATDelay = 100 |
| 73 |
maxCloseDelay = 60 |
| 74 |
) |
| 75 |
|
| 76 |
const ( |
| 77 |
iatNone = iota |
| 78 |
iatEnabled |
| 79 |
iatParanoid |
| 80 |
) |
| 81 |
|
| 82 |
// biasedDist controls if the probability table will be ScrambleSuit style or |
| 83 |
// uniformly distributed. |
| 84 |
var biasedDist bool |
| 85 |
|
| 86 |
type obfs4ClientArgs struct { |
| 87 |
nodeID *ntor.NodeID |
| 88 |
publicKey *ntor.PublicKey |
| 89 |
sessionKey *ntor.Keypair |
| 90 |
iatMode int |
| 91 |
} |
| 92 |
|
| 93 |
// Transport is the obfs4 implementation of the base.Transport interface. |
| 94 |
type Transport struct{} |
| 95 |
|
| 96 |
// Name returns the name of the obfs4 transport protocol. |
| 97 |
func (t *Transport) Name() string { |
| 98 |
return transportName |
| 99 |
} |
| 100 |
|
| 101 |
// ClientFactory returns a new obfs4ClientFactory instance. |
| 102 |
func (t *Transport) ClientFactory(stateDir string) (base.ClientFactory, error) { |
| 103 |
cf := &obfs4ClientFactory{transport: t} |
| 104 |
return cf, nil |
| 105 |
} |
| 106 |
|
| 107 |
// ServerFactory returns a new obfs4ServerFactory instance. |
| 108 |
func (t *Transport) ServerFactory(stateDir string, args *pt.Args) (base.ServerFactory, error) { |
| 109 |
st, err := serverStateFromArgs(stateDir, args) |
| 110 |
if err != nil { |
| 111 |
return nil, err |
| 112 |
} |
| 113 |
|
| 114 |
var iatSeed *drbg.Seed |
| 115 |
if st.iatMode != iatNone { |
| 116 |
iatSeedSrc := sha256.Sum256(st.drbgSeed.Bytes()[:]) |
| 117 |
var err error |
| 118 |
iatSeed, err = drbg.SeedFromBytes(iatSeedSrc[:]) |
| 119 |
if err != nil { |
| 120 |
return nil, err |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
// Store the arguments that should appear in our descriptor for the clients. |
| 125 |
ptArgs := pt.Args{} |
| 126 |
ptArgs.Add(certArg, st.cert.String()) |
| 127 |
ptArgs.Add(iatArg, strconv.Itoa(st.iatMode)) |
| 128 |
|
| 129 |
// Initialize the replay filter. |
| 130 |
filter, err := replayfilter.New(replayTTL) |
| 131 |
if err != nil { |
| 132 |
return nil, err |
| 133 |
} |
| 134 |
|
| 135 |
// Initialize the close thresholds for failed connections. |
| 136 |
drbg, err := drbg.NewHashDrbg(st.drbgSeed) |
| 137 |
if err != nil { |
| 138 |
return nil, err |
| 139 |
} |
| 140 |
rng := rand.New(drbg) |
| 141 |
|
| 142 |
sf := &obfs4ServerFactory{t, &ptArgs, st.nodeID, st.identityKey, st.drbgSeed, iatSeed, st.iatMode, filter, rng.Intn(maxCloseDelay)} |
| 143 |
return sf, nil |
| 144 |
} |
| 145 |
|
| 146 |
type obfs4ClientFactory struct { |
| 147 |
transport base.Transport |
| 148 |
} |
| 149 |
|
| 150 |
func (cf *obfs4ClientFactory) Transport() base.Transport { |
| 151 |
return cf.transport |
| 152 |
} |
| 153 |
|
| 154 |
func (cf *obfs4ClientFactory) ParseArgs(args *pt.Args) (interface{}, error) { |
| 155 |
var nodeID *ntor.NodeID |
| 156 |
var publicKey *ntor.PublicKey |
| 157 |
|
| 158 |
// The "new" (version >= 0.0.3) bridge lines use a unified "cert" argument |
| 159 |
// for the Node ID and Public Key. |
| 160 |
certStr, ok := args.Get(certArg) |
| 161 |
if ok { |
| 162 |
cert, err := serverCertFromString(certStr) |
| 163 |
if err != nil { |
| 164 |
return nil, err |
| 165 |
} |
| 166 |
nodeID, publicKey = cert.unpack() |
| 167 |
} else { |
| 168 |
// The "old" style (version <= 0.0.2) bridge lines use separate Node ID |
| 169 |
// and Public Key arguments in Base16 encoding and are a UX disaster. |
| 170 |
nodeIDStr, ok := args.Get(nodeIDArg) |
| 171 |
if !ok { |
| 172 |
return nil, fmt.Errorf("missing argument '%s'", nodeIDArg) |
| 173 |
} |
| 174 |
var err error |
| 175 |
if nodeID, err = ntor.NodeIDFromHex(nodeIDStr); err != nil { |
| 176 |
return nil, err |
| 177 |
} |
| 178 |
|
| 179 |
publicKeyStr, ok := args.Get(publicKeyArg) |
| 180 |
if !ok { |
| 181 |
return nil, fmt.Errorf("missing argument '%s'", publicKeyArg) |
| 182 |
} |
| 183 |
if publicKey, err = ntor.PublicKeyFromHex(publicKeyStr); err != nil { |
| 184 |
return nil, err |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// IAT config is common across the two bridge line formats. |
| 189 |
iatStr, ok := args.Get(iatArg) |
| 190 |
if !ok { |
| 191 |
return nil, fmt.Errorf("missing argument '%s'", iatArg) |
| 192 |
} |
| 193 |
iatMode, err := strconv.Atoi(iatStr) |
| 194 |
if err != nil || iatMode < iatNone || iatMode > iatParanoid { |
| 195 |
return nil, fmt.Errorf("invalid iat-mode '%d'", iatMode) |
| 196 |
} |
| 197 |
|
| 198 |
// Generate the session key pair before connectiong to hide the Elligator2 |
| 199 |
// rejection sampling from network observers. |
| 200 |
sessionKey, err := ntor.NewKeypair(true) |
| 201 |
if err != nil { |
| 202 |
return nil, err |
| 203 |
} |
| 204 |
|
| 205 |
return &obfs4ClientArgs{nodeID, publicKey, sessionKey, iatMode}, nil |
| 206 |
} |
| 207 |
|
| 208 |
func (cf *obfs4ClientFactory) Dial(network, addr string, dialFn base.DialFunc, args interface{}) (net.Conn, error) { |
| 209 |
// Validate args before bothering to open connection. |
| 210 |
ca, ok := args.(*obfs4ClientArgs) |
| 211 |
if !ok { |
| 212 |
return nil, fmt.Errorf("invalid argument type for args") |
| 213 |
} |
| 214 |
conn, err := dialFn(network, addr) |
| 215 |
if err != nil { |
| 216 |
return nil, err |
| 217 |
} |
| 218 |
dialConn := conn |
| 219 |
if conn, err = newObfs4ClientConn(conn, ca); err != nil { |
| 220 |
dialConn.Close() |
| 221 |
return nil, err |
| 222 |
} |
| 223 |
return conn, nil |
| 224 |
} |
| 225 |
|
| 226 |
type obfs4ServerFactory struct { |
| 227 |
transport base.Transport |
| 228 |
args *pt.Args |
| 229 |
|
| 230 |
nodeID *ntor.NodeID |
| 231 |
identityKey *ntor.Keypair |
| 232 |
lenSeed *drbg.Seed |
| 233 |
iatSeed *drbg.Seed |
| 234 |
iatMode int |
| 235 |
replayFilter *replayfilter.ReplayFilter |
| 236 |
|
| 237 |
closeDelay int |
| 238 |
} |
| 239 |
|
| 240 |
func (sf *obfs4ServerFactory) Transport() base.Transport { |
| 241 |
return sf.transport |
| 242 |
} |
| 243 |
|
| 244 |
func (sf *obfs4ServerFactory) Args() *pt.Args { |
| 245 |
return sf.args |
| 246 |
} |
| 247 |
|
| 248 |
func (sf *obfs4ServerFactory) WrapConn(conn net.Conn) (net.Conn, error) { |
| 249 |
// Not much point in having a separate newObfs4ServerConn routine when |
| 250 |
// wrapping requires using values from the factory instance. |
| 251 |
|
| 252 |
// Generate the session keypair *before* consuming data from the peer, to |
| 253 |
// attempt to mask the rejection sampling due to use of Elligator2. This |
| 254 |
// might be futile, but the timing differential isn't very large on modern |
| 255 |
// hardware, and there are far easier statistical attacks that can be |
| 256 |
// mounted as a distinguisher. |
| 257 |
sessionKey, err := ntor.NewKeypair(true) |
| 258 |
if err != nil { |
| 259 |
return nil, err |
| 260 |
} |
| 261 |
|
| 262 |
lenDist := probdist.New(sf.lenSeed, 0, framing.MaximumSegmentLength, biasedDist) |
| 263 |
var iatDist *probdist.WeightedDist |
| 264 |
if sf.iatSeed != nil { |
| 265 |
iatDist = probdist.New(sf.iatSeed, 0, maxIATDelay, biasedDist) |
| 266 |
} |
| 267 |
|
| 268 |
c := &obfs4Conn{conn, true, lenDist, iatDist, sf.iatMode, bytes.NewBuffer(nil), bytes.NewBuffer(nil), make([]byte, consumeReadSize), nil, nil} |
| 269 |
|
| 270 |
startTime := time.Now() |
| 271 |
|
| 272 |
if err = c.serverHandshake(sf, sessionKey); err != nil { |
| 273 |
c.closeAfterDelay(sf, startTime) |
| 274 |
return nil, err |
| 275 |
} |
| 276 |
|
| 277 |
return c, nil |
| 278 |
} |
| 279 |
|
| 280 |
type obfs4Conn struct { |
| 281 |
net.Conn |
| 282 |
|
| 283 |
isServer bool |
| 284 |
|
| 285 |
lenDist *probdist.WeightedDist |
| 286 |
iatDist *probdist.WeightedDist |
| 287 |
iatMode int |
| 288 |
|
| 289 |
receiveBuffer *bytes.Buffer |
| 290 |
receiveDecodedBuffer *bytes.Buffer |
| 291 |
readBuffer []byte |
| 292 |
|
| 293 |
encoder *framing.Encoder |
| 294 |
decoder *framing.Decoder |
| 295 |
} |
| 296 |
|
| 297 |
func newObfs4ClientConn(conn net.Conn, args *obfs4ClientArgs) (c *obfs4Conn, err error) { |
| 298 |
// Generate the initial protocol polymorphism distribution(s). |
| 299 |
var seed *drbg.Seed |
| 300 |
if seed, err = drbg.NewSeed(); err != nil { |
| 301 |
return |
| 302 |
} |
| 303 |
lenDist := probdist.New(seed, 0, framing.MaximumSegmentLength, biasedDist) |
| 304 |
var iatDist *probdist.WeightedDist |
| 305 |
if args.iatMode != iatNone { |
| 306 |
var iatSeed *drbg.Seed |
| 307 |
iatSeedSrc := sha256.Sum256(seed.Bytes()[:]) |
| 308 |
if iatSeed, err = drbg.SeedFromBytes(iatSeedSrc[:]); err != nil { |
| 309 |
return |
| 310 |
} |
| 311 |
iatDist = probdist.New(iatSeed, 0, maxIATDelay, biasedDist) |
| 312 |
} |
| 313 |
|
| 314 |
// Allocate the client structure. |
| 315 |
c = &obfs4Conn{conn, false, lenDist, iatDist, args.iatMode, bytes.NewBuffer(nil), bytes.NewBuffer(nil), make([]byte, consumeReadSize), nil, nil} |
| 316 |
|
| 317 |
// Start the handshake timeout. |
| 318 |
deadline := time.Now().Add(clientHandshakeTimeout) |
| 319 |
if err = conn.SetDeadline(deadline); err != nil { |
| 320 |
return nil, err |
| 321 |
} |
| 322 |
|
| 323 |
if err = c.clientHandshake(args.nodeID, args.publicKey, args.sessionKey); err != nil { |
| 324 |
return nil, err |
| 325 |
} |
| 326 |
|
| 327 |
// Stop the handshake timeout. |
| 328 |
if err = conn.SetDeadline(time.Time{}); err != nil { |
| 329 |
return nil, err |
| 330 |
} |
| 331 |
|
| 332 |
return |
| 333 |
} |
| 334 |
|
| 335 |
func (conn *obfs4Conn) clientHandshake(nodeID *ntor.NodeID, peerIdentityKey *ntor.PublicKey, sessionKey *ntor.Keypair) error { |
| 336 |
if conn.isServer { |
| 337 |
return fmt.Errorf("clientHandshake called on server connection") |
| 338 |
} |
| 339 |
|
| 340 |
// Generate and send the client handshake. |
| 341 |
hs := newClientHandshake(nodeID, peerIdentityKey, sessionKey) |
| 342 |
blob, err := hs.generateHandshake() |
| 343 |
if err != nil { |
| 344 |
return err |
| 345 |
} |
| 346 |
if _, err = conn.Conn.Write(blob); err != nil { |
| 347 |
return err |
| 348 |
} |
| 349 |
|
| 350 |
// Consume the server handshake. |
| 351 |
var hsBuf [maxHandshakeLength]byte |
| 352 |
for { |
| 353 |
n, err := conn.Conn.Read(hsBuf[:]) |
| 354 |
if err != nil { |
| 355 |
// The Read() could have returned data and an error, but there is |
| 356 |
// no point in continuing on an EOF or whatever. |
| 357 |
return err |
| 358 |
} |
| 359 |
conn.receiveBuffer.Write(hsBuf[:n]) |
| 360 |
|
| 361 |
n, seed, err := hs.parseServerHandshake(conn.receiveBuffer.Bytes()) |
| 362 |
if err == ErrMarkNotFoundYet { |
| 363 |
continue |
| 364 |
} else if err != nil { |
| 365 |
return err |
| 366 |
} |
| 367 |
_ = conn.receiveBuffer.Next(n) |
| 368 |
|
| 369 |
// Use the derived key material to intialize the link crypto. |
| 370 |
okm := ntor.Kdf(seed, framing.KeyLength*2) |
| 371 |
conn.encoder = framing.NewEncoder(okm[:framing.KeyLength]) |
| 372 |
conn.decoder = framing.NewDecoder(okm[framing.KeyLength:]) |
| 373 |
|
| 374 |
return nil |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
func (conn *obfs4Conn) serverHandshake(sf *obfs4ServerFactory, sessionKey *ntor.Keypair) error { |
| 379 |
if !conn.isServer { |
| 380 |
return fmt.Errorf("serverHandshake called on client connection") |
| 381 |
} |
| 382 |
|
| 383 |
// Generate the server handshake, and arm the base timeout. |
| 384 |
hs := newServerHandshake(sf.nodeID, sf.identityKey, sessionKey) |
| 385 |
if err := conn.Conn.SetDeadline(time.Now().Add(serverHandshakeTimeout)); err != nil { |
| 386 |
return err |
| 387 |
} |
| 388 |
|
| 389 |
// Consume the client handshake. |
| 390 |
var hsBuf [maxHandshakeLength]byte |
| 391 |
for { |
| 392 |
n, err := conn.Conn.Read(hsBuf[:]) |
| 393 |
if err != nil { |
| 394 |
// The Read() could have returned data and an error, but there is |
| 395 |
// no point in continuing on an EOF or whatever. |
| 396 |
return err |
| 397 |
} |
| 398 |
conn.receiveBuffer.Write(hsBuf[:n]) |
| 399 |
|
| 400 |
seed, err := hs.parseClientHandshake(sf.replayFilter, conn.receiveBuffer.Bytes()) |
| 401 |
if err == ErrMarkNotFoundYet { |
| 402 |
continue |
| 403 |
} else if err != nil { |
| 404 |
return err |
| 405 |
} |
| 406 |
conn.receiveBuffer.Reset() |
| 407 |
|
| 408 |
if err := conn.Conn.SetDeadline(time.Time{}); err != nil { |
| 409 |
return nil |
| 410 |
} |
| 411 |
|
| 412 |
// Use the derived key material to intialize the link crypto. |
| 413 |
okm := ntor.Kdf(seed, framing.KeyLength*2) |
| 414 |
conn.encoder = framing.NewEncoder(okm[framing.KeyLength:]) |
| 415 |
conn.decoder = framing.NewDecoder(okm[:framing.KeyLength]) |
| 416 |
|
| 417 |
break |
| 418 |
} |
| 419 |
|
| 420 |
// Since the current and only implementation always sends a PRNG seed for |
| 421 |
// the length obfuscation, this makes the amount of data received from the |
| 422 |
// server inconsistent with the length sent from the client. |
| 423 |
// |
| 424 |
// Rebalance this by tweaking the client mimimum padding/server maximum |
| 425 |
// padding, and sending the PRNG seed unpadded (As in, treat the PRNG seed |
| 426 |
// as part of the server response). See inlineSeedFrameLength in |
| 427 |
// handshake_ntor.go. |
| 428 |
|
| 429 |
// Generate/send the response. |
| 430 |
blob, err := hs.generateHandshake() |
| 431 |
if err != nil { |
| 432 |
return err |
| 433 |
} |
| 434 |
var frameBuf bytes.Buffer |
| 435 |
if _, err = frameBuf.Write(blob); err != nil { |
| 436 |
return err |
| 437 |
} |
| 438 |
|
| 439 |
// Send the PRNG seed as the first packet. |
| 440 |
if err := conn.makePacket(&frameBuf, packetTypePrngSeed, sf.lenSeed.Bytes()[:], 0); err != nil { |
| 441 |
return err |
| 442 |
} |
| 443 |
if _, err = conn.Conn.Write(frameBuf.Bytes()); err != nil { |
| 444 |
return err |
| 445 |
} |
| 446 |
|
| 447 |
return nil |
| 448 |
} |
| 449 |
|
| 450 |
func (conn *obfs4Conn) Read(b []byte) (n int, err error) { |
| 451 |
// If there is no payload from the previous Read() calls, consume data off |
| 452 |
// the network. Not all data received is guaranteed to be usable payload, |
| 453 |
// so do this in a loop till data is present or an error occurs. |
| 454 |
for conn.receiveDecodedBuffer.Len() == 0 { |
| 455 |
err = conn.readPackets() |
| 456 |
if err == framing.ErrAgain { |
| 457 |
// Don't proagate this back up the call stack if we happen to break |
| 458 |
// out of the loop. |
| 459 |
err = nil |
| 460 |
continue |
| 461 |
} else if err != nil { |
| 462 |
break |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
// Even if err is set, attempt to do the read anyway so that all decoded |
| 467 |
// data gets relayed before the connection is torn down. |
| 468 |
if conn.receiveDecodedBuffer.Len() > 0 { |
| 469 |
var berr error |
| 470 |
n, berr = conn.receiveDecodedBuffer.Read(b) |
| 471 |
if err == nil { |
| 472 |
// Only propagate berr if there are not more important (fatal) |
| 473 |
// errors from the network/crypto/packet processing. |
| 474 |
err = berr |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
return |
| 479 |
} |
| 480 |
|
| 481 |
func (conn *obfs4Conn) Write(b []byte) (n int, err error) { |
| 482 |
chopBuf := bytes.NewBuffer(b) |
| 483 |
var payload [maxPacketPayloadLength]byte |
| 484 |
var frameBuf bytes.Buffer |
| 485 |
|
| 486 |
// Chop the pending data into payload frames. |
| 487 |
for chopBuf.Len() > 0 { |
| 488 |
// Send maximum sized frames. |
| 489 |
rdLen := 0 |
| 490 |
rdLen, err = chopBuf.Read(payload[:]) |
| 491 |
if err != nil { |
| 492 |
return 0, err |
| 493 |
} else if rdLen == 0 { |
| 494 |
panic(fmt.Sprintf("BUG: Write(), chopping length was 0")) |
| 495 |
} |
| 496 |
n += rdLen |
| 497 |
|
| 498 |
err = conn.makePacket(&frameBuf, packetTypePayload, payload[:rdLen], 0) |
| 499 |
if err != nil { |
| 500 |
return 0, err |
| 501 |
} |
| 502 |
} |
| 503 |
|
| 504 |
if conn.iatMode != iatParanoid { |
| 505 |
// For non-paranoid IAT, pad once per burst. Paranoid IAT handles |
| 506 |
// things differently. |
| 507 |
if err = conn.padBurst(&frameBuf, conn.lenDist.Sample()); err != nil { |
| 508 |
return 0, err |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
// Write the pending data onto the network. Partial writes are fatal, |
| 513 |
// because the frame encoder state is advanced, and the code doesn't keep |
| 514 |
// frameBuf around. In theory, write timeouts and whatnot could be |
| 515 |
// supported if this wasn't the case, but that complicates the code. |
| 516 |
if conn.iatMode != iatNone { |
| 517 |
var iatFrame [framing.MaximumSegmentLength]byte |
| 518 |
for frameBuf.Len() > 0 { |
| 519 |
iatWrLen := 0 |
| 520 |
|
| 521 |
switch conn.iatMode { |
| 522 |
case iatEnabled: |
| 523 |
// Standard (ScrambleSuit-style) IAT obfuscation optimizes for |
| 524 |
// bulk transport and will write ~MTU sized frames when |
| 525 |
// possible. |
| 526 |
iatWrLen, err = frameBuf.Read(iatFrame[:]) |
| 527 |
|
| 528 |
case iatParanoid: |
| 529 |
// Paranoid IAT obfuscation throws performance out of the |
| 530 |
// window and will sample the length distribution every time a |
| 531 |
// write is scheduled. |
| 532 |
targetLen := conn.lenDist.Sample() |
| 533 |
if frameBuf.Len() < targetLen { |
| 534 |
// There's not enough data buffered for the target write, |
| 535 |
// so padding must be inserted. |
| 536 |
if err = conn.padBurst(&frameBuf, targetLen); err != nil { |
| 537 |
return 0, err |
| 538 |
} |
| 539 |
if frameBuf.Len() != targetLen { |
| 540 |
// Ugh, padding came out to a value that required more |
| 541 |
// than one frame, this is relatively unlikely so just |
| 542 |
// resample since there's enough data to ensure that |
| 543 |
// the next sample will be written. |
| 544 |
continue |
| 545 |
} |
| 546 |
} |
| 547 |
iatWrLen, err = frameBuf.Read(iatFrame[:targetLen]) |
| 548 |
} |
| 549 |
if err != nil { |
| 550 |
return 0, err |
| 551 |
} else if iatWrLen == 0 { |
| 552 |
panic(fmt.Sprintf("BUG: Write(), iat length was 0")) |
| 553 |
} |
| 554 |
|
| 555 |
// Calculate the delay. The delay resolution is 100 usec, leading |
| 556 |
// to a maximum delay of 10 msec. |
| 557 |
iatDelta := time.Duration(conn.iatDist.Sample() * 100) |
| 558 |
|
| 559 |
// Write then sleep. |
| 560 |
_, err = conn.Conn.Write(iatFrame[:iatWrLen]) |
| 561 |
if err != nil { |
| 562 |
return 0, err |
| 563 |
} |
| 564 |
time.Sleep(iatDelta * time.Microsecond) |
| 565 |
} |
| 566 |
} else { |
| 567 |
_, err = conn.Conn.Write(frameBuf.Bytes()) |
| 568 |
} |
| 569 |
|
| 570 |
return |
| 571 |
} |
| 572 |
|
| 573 |
func (conn *obfs4Conn) SetDeadline(t time.Time) error { |
| 574 |
return syscall.ENOTSUP |
| 575 |
} |
| 576 |
|
| 577 |
func (conn *obfs4Conn) SetWriteDeadline(t time.Time) error { |
| 578 |
return syscall.ENOTSUP |
| 579 |
} |
| 580 |
|
| 581 |
func (conn *obfs4Conn) closeAfterDelay(sf *obfs4ServerFactory, startTime time.Time) { |
| 582 |
// I-it's not like I w-wanna handshake with you or anything. B-b-baka! |
| 583 |
defer conn.Conn.Close() |
| 584 |
|
| 585 |
delay := time.Duration(sf.closeDelay)*time.Second + serverHandshakeTimeout |
| 586 |
deadline := startTime.Add(delay) |
| 587 |
if time.Now().After(deadline) { |
| 588 |
return |
| 589 |
} |
| 590 |
|
| 591 |
if err := conn.Conn.SetReadDeadline(deadline); err != nil { |
| 592 |
return |
| 593 |
} |
| 594 |
|
| 595 |
// Consume and discard data on this connection until the specified interval |
| 596 |
// passes. |
| 597 |
_, _ = io.Copy(ioutil.Discard, conn.Conn) |
| 598 |
} |
| 599 |
|
| 600 |
func (conn *obfs4Conn) padBurst(burst *bytes.Buffer, toPadTo int) (err error) { |
| 601 |
tailLen := burst.Len() % framing.MaximumSegmentLength |
| 602 |
|
| 603 |
padLen := 0 |
| 604 |
if toPadTo >= tailLen { |
| 605 |
padLen = toPadTo - tailLen |
| 606 |
} else { |
| 607 |
padLen = (framing.MaximumSegmentLength - tailLen) + toPadTo |
| 608 |
} |
| 609 |
|
| 610 |
if padLen > headerLength { |
| 611 |
err = conn.makePacket(burst, packetTypePayload, []byte{}, |
| 612 |
uint16(padLen-headerLength)) |
| 613 |
if err != nil { |
| 614 |
return |
| 615 |
} |
| 616 |
} else if padLen > 0 { |
| 617 |
err = conn.makePacket(burst, packetTypePayload, []byte{}, |
| 618 |
maxPacketPayloadLength) |
| 619 |
if err != nil { |
| 620 |
return |
| 621 |
} |
| 622 |
err = conn.makePacket(burst, packetTypePayload, []byte{}, |
| 623 |
uint16(padLen)) |
| 624 |
if err != nil { |
| 625 |
return |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
return |
| 630 |
} |
| 631 |
|
| 632 |
func init() { |
| 633 |
flag.BoolVar(&biasedDist, biasCmdArg, false, "Enable obfs4 using ScrambleSuit style table generation") |
| 634 |
} |
| 635 |
|
| 636 |
var _ base.ClientFactory = (*obfs4ClientFactory)(nil) |
| 637 |
var _ base.ServerFactory = (*obfs4ServerFactory)(nil) |
| 638 |
var _ base.Transport = (*Transport)(nil) |
| 639 |
var _ net.Conn = (*obfs4Conn)(nil) |