obfuscator.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. //go:build !PSIPHON_DISABLE_QUIC
  2. // +build !PSIPHON_DISABLE_QUIC
  3. /*
  4. * Copyright (c) 2018, Psiphon Inc.
  5. * All rights reserved.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package quic
  22. import (
  23. "crypto/sha256"
  24. std_errors "errors"
  25. "io"
  26. "net"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/Yawning/chacha20"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  35. ietf_quic "github.com/Psiphon-Labs/quic-go"
  36. "golang.org/x/crypto/hkdf"
  37. "golang.org/x/net/ipv4"
  38. )
  39. const (
  40. // MAX_PACKET_SIZE is the largest packet size quic-go will produce,
  41. // including post MTU discovery. This value is quic-go
  42. // internal/protocol.MaxPacketBufferSize, which is the Ethernet MTU of
  43. // 1500 less IPv6 and UDP header sizes.
  44. //
  45. // Legacy gQUIC quic-go will produce packets no larger than
  46. // MAX_PRE_DISCOVERY_PACKET_SIZE_IPV4/IPV6.
  47. MAX_PACKET_SIZE = 1452
  48. // MAX_PRE_DISCOVERY_PACKET_SIZE_IPV4/IPV6 are the largest packet sizes
  49. // quic-go will produce before MTU discovery, 1280 less IP and UDP header
  50. // sizes. These values, which match quic-go
  51. // internal/protocol.InitialPacketSizeIPv4/IPv6, are used to calculate
  52. // maximum padding sizes.
  53. MAX_PRE_DISCOVERY_PACKET_SIZE_IPV4 = 1252
  54. MAX_PRE_DISCOVERY_PACKET_SIZE_IPV6 = 1232
  55. // OBFUSCATED_MAX_PACKET_SIZE_ADJUSTMENT is the minimum amount of bytes
  56. // required for obfuscation overhead, the nonce and the padding length.
  57. // In IETF quic-go, this adjustment value is passed into quic-go and
  58. // applied to packet construction so that quic-go produces max packet
  59. // sizes reduced by this adjustment value.
  60. OBFUSCATED_MAX_PACKET_SIZE_ADJUSTMENT = NONCE_SIZE + 1
  61. // MIN_INITIAL_PACKET_SIZE is the minimum UDP packet payload size for
  62. // Initial packets, an anti-amplification measure (see RFC 9000, section
  63. // 14.1). To accomodate obfuscation prefix messages within the same
  64. // Initial UDP packet, quic-go's enforcement of this size requirement is
  65. // disabled and the enforcment is done by ObfuscatedPacketConn.
  66. MIN_INITIAL_PACKET_SIZE = 1200
  67. MAX_PADDING_SIZE = 255
  68. MAX_GQUIC_PADDING_SIZE = 64
  69. MIN_DECOY_PACKETS = 0
  70. MAX_DECOY_PACKETS = 10
  71. NONCE_SIZE = 12
  72. RANDOM_STREAM_LIMIT = 1<<38 - 64
  73. CONCURRENT_WRITER_LIMIT = 5000
  74. )
  75. // ObfuscatedPacketConn wraps a QUIC net.PacketConn with an obfuscation layer
  76. // that obscures QUIC packets, adding random padding and producing uniformly
  77. // random payload.
  78. //
  79. // The crypto performed by ObfuscatedPacketConn is purely for obfuscation to
  80. // frustrate wire-speed DPI and does not add privacy/security. The small
  81. // nonce space and single key per server is not cryptographically secure.
  82. //
  83. // A server-side ObfuscatedPacketConn performs simple QUIC DPI to distinguish
  84. // between obfuscated and non-obfsucated peer flows and responds accordingly.
  85. //
  86. // The header and padding added by ObfuscatedPacketConn on top of the QUIC
  87. // payload will increase UDP packets beyond the QUIC max of 1280 bytes,
  88. // introducing some risk of fragmentation and/or dropped packets.
  89. type ObfuscatedPacketConn struct {
  90. net.PacketConn
  91. remoteAddr *net.UDPAddr
  92. isServer bool
  93. isIETFClient bool
  94. isDecoyClient bool
  95. isClosed int32
  96. runWaitGroup *sync.WaitGroup
  97. stopBroadcast chan struct{}
  98. obfuscationKey [32]byte
  99. peerModesMutex sync.Mutex
  100. peerModes map[string]*peerMode
  101. noncePRNG *prng.PRNG
  102. paddingPRNG *prng.PRNG
  103. nonceTransformerParameters *transforms.ObfuscatorSeedTransformerParameters
  104. decoyPacketCount int32
  105. decoyBuffer []byte
  106. concurrentWriters int32
  107. }
  108. type peerMode struct {
  109. isObfuscated bool
  110. isIETF bool
  111. lastPacketTime time.Time
  112. }
  113. func (p *peerMode) isStale() bool {
  114. return time.Since(p.lastPacketTime) >= SERVER_IDLE_TIMEOUT
  115. }
  116. func NewClientObfuscatedPacketConn(
  117. packetConn net.PacketConn,
  118. remoteAddr *net.UDPAddr,
  119. isIETFClient bool,
  120. isDecoyClient bool,
  121. obfuscationKey string,
  122. paddingSeed *prng.Seed,
  123. obfuscationNonceTransformerParameters *transforms.ObfuscatorSeedTransformerParameters,
  124. ) (*ObfuscatedPacketConn, error) {
  125. return newObfuscatedPacketConn(
  126. packetConn,
  127. remoteAddr,
  128. false,
  129. isIETFClient,
  130. isDecoyClient,
  131. obfuscationKey,
  132. paddingSeed,
  133. obfuscationNonceTransformerParameters)
  134. }
  135. func NewServerObfuscatedPacketConn(
  136. packetConn net.PacketConn,
  137. isIETFClient bool,
  138. isDecoyClient bool,
  139. obfuscationKey string,
  140. paddingSeed *prng.Seed) (*ObfuscatedPacketConn, error) {
  141. return newObfuscatedPacketConn(
  142. packetConn,
  143. nil,
  144. true,
  145. isIETFClient,
  146. isDecoyClient,
  147. obfuscationKey,
  148. paddingSeed,
  149. nil)
  150. }
  151. // newObfuscatedPacketConn creates a new ObfuscatedPacketConn.
  152. func newObfuscatedPacketConn(
  153. packetConn net.PacketConn,
  154. remoteAddr *net.UDPAddr,
  155. isServer bool,
  156. isIETFClient bool,
  157. isDecoyClient bool,
  158. obfuscationKey string,
  159. paddingSeed *prng.Seed,
  160. obfuscationNonceTransformerParameters *transforms.ObfuscatorSeedTransformerParameters,
  161. ) (*ObfuscatedPacketConn, error) {
  162. // Store the specified remoteAddr, which is used to implement
  163. // net.Conn.RemoteAddr, as the input packetConn may return a nil remote
  164. // addr from ReadFrom. This must be set and is only set for clients.
  165. if isServer != (remoteAddr == nil) {
  166. return nil, errors.TraceNew("invalid remoteAddr")
  167. }
  168. // There is no replay of obfuscation "encryption", just padding.
  169. nonceSeed, err := prng.NewSeed()
  170. if err != nil {
  171. return nil, errors.Trace(err)
  172. }
  173. conn := &ObfuscatedPacketConn{
  174. PacketConn: packetConn,
  175. remoteAddr: remoteAddr,
  176. isServer: isServer,
  177. isIETFClient: isIETFClient,
  178. isDecoyClient: isDecoyClient,
  179. peerModes: make(map[string]*peerMode),
  180. noncePRNG: prng.NewPRNGWithSeed(nonceSeed),
  181. paddingPRNG: prng.NewPRNGWithSeed(paddingSeed),
  182. nonceTransformerParameters: obfuscationNonceTransformerParameters,
  183. }
  184. secret := []byte(obfuscationKey)
  185. salt := []byte("quic-obfuscation-key")
  186. _, err = io.ReadFull(
  187. hkdf.New(sha256.New, secret, salt, nil), conn.obfuscationKey[:])
  188. if err != nil {
  189. return nil, errors.Trace(err)
  190. }
  191. if isDecoyClient {
  192. conn.decoyPacketCount = int32(conn.paddingPRNG.Range(
  193. MIN_DECOY_PACKETS, MAX_DECOY_PACKETS))
  194. conn.decoyBuffer = make([]byte, MAX_PACKET_SIZE)
  195. }
  196. if isServer {
  197. conn.runWaitGroup = new(sync.WaitGroup)
  198. conn.stopBroadcast = make(chan struct{})
  199. // Reap stale peer mode information to reclaim memory.
  200. conn.runWaitGroup.Add(1)
  201. go func() {
  202. defer conn.runWaitGroup.Done()
  203. ticker := time.NewTicker(SERVER_IDLE_TIMEOUT / 2)
  204. defer ticker.Stop()
  205. for {
  206. select {
  207. case <-ticker.C:
  208. conn.peerModesMutex.Lock()
  209. for address, mode := range conn.peerModes {
  210. if mode.isStale() {
  211. delete(conn.peerModes, address)
  212. }
  213. }
  214. conn.peerModesMutex.Unlock()
  215. case <-conn.stopBroadcast:
  216. return
  217. }
  218. }
  219. }()
  220. }
  221. return conn, nil
  222. }
  223. func (conn *ObfuscatedPacketConn) Close() error {
  224. // Ensure close channel only called once.
  225. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  226. return nil
  227. }
  228. if conn.isServer {
  229. // Interrupt any blocked writes.
  230. conn.PacketConn.SetWriteDeadline(time.Now())
  231. close(conn.stopBroadcast)
  232. conn.runWaitGroup.Wait()
  233. }
  234. return conn.PacketConn.Close()
  235. }
  236. type temporaryNetError struct {
  237. err error
  238. }
  239. func newTemporaryNetError(err error) *temporaryNetError {
  240. return &temporaryNetError{err: err}
  241. }
  242. func (e *temporaryNetError) Timeout() bool {
  243. return false
  244. }
  245. func (e *temporaryNetError) Temporary() bool {
  246. return true
  247. }
  248. func (e *temporaryNetError) Error() string {
  249. return e.err.Error()
  250. }
  251. func (conn *ObfuscatedPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
  252. n, _, _, addr, _, err := conn.readPacketWithType(p, nil)
  253. // Do not wrap any I/O err returned by conn.PacketConn
  254. return n, addr, err
  255. }
  256. func (conn *ObfuscatedPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
  257. udpAddr, ok := addr.(*net.UDPAddr)
  258. if !ok {
  259. return 0, errors.TraceNew("unexpected addr type")
  260. }
  261. n, _, err := conn.writePacket(p, nil, udpAddr)
  262. // Do not wrap any I/O err returned by conn.PacketConn
  263. return n, err
  264. }
  265. // ReadMsgUDP, and WriteMsgUDP satisfy the ietf_quic.OOBCapablePacketConn
  266. // interface. In non-muxListener mode, quic-go will access the
  267. // ObfuscatedPacketConn directly and use these functions to set ECN bits.
  268. //
  269. // ReadBatch implements ietf_quic.batchConn. Providing this implementation
  270. // effectively disables the quic-go batch packet reading optimization, which
  271. // would otherwise bypass deobfuscation. Note that ipv4.Message is an alias
  272. // for x/net/internal/socket.Message and quic-go uses this one type for both
  273. // IPv4 and IPv6 packets.
  274. //
  275. // Read and Write are present to satisfy the net.Conn interface, to which
  276. // ObfuscatedPacketConn is converted internally, via quic-go, in x/net/ipv
  277. // [4|6] for OOB manipulation. These functions do not need to be
  278. // implemented.
  279. func (conn *ObfuscatedPacketConn) ReadMsgUDP(p, oob []byte) (int, int, int, *net.UDPAddr, error) {
  280. n, oobn, flags, addr, _, err := conn.readPacketWithType(p, nil)
  281. // Do not wrap any I/O err returned by conn.PacketConn
  282. return n, oobn, flags, addr, err
  283. }
  284. func (conn *ObfuscatedPacketConn) WriteMsgUDP(p, oob []byte, addr *net.UDPAddr) (int, int, error) {
  285. n, oobn, err := conn.writePacket(p, oob, addr)
  286. // Do not wrap any I/O err returned by conn.PacketConn
  287. return n, oobn, err
  288. }
  289. func (conn *ObfuscatedPacketConn) ReadBatch(ms []ipv4.Message, _ int) (int, error) {
  290. // Read a "batch" of 1 message, with any necessary deobfuscation performed
  291. // by readPacketWithType.
  292. //
  293. // TODO: implement proper batch packet reading here, along with batch
  294. // deobfuscation.
  295. if len(ms) < 1 || len(ms[0].Buffers[0]) < 1 {
  296. return 0, errors.TraceNew("unexpected message buffer size")
  297. }
  298. var err error
  299. ms[0].N, ms[0].NN, ms[0].Flags, ms[0].Addr, _, err =
  300. conn.readPacketWithType(ms[0].Buffers[0], ms[0].OOB)
  301. if err != nil {
  302. // Do not wrap any I/O err returned by conn.PacketConn
  303. return 0, err
  304. }
  305. return 1, nil
  306. }
  307. var notSupported = std_errors.New("not supported")
  308. func (conn *ObfuscatedPacketConn) Read(_ []byte) (int, error) {
  309. return 0, errors.Trace(notSupported)
  310. }
  311. func (conn *ObfuscatedPacketConn) Write(_ []byte) (int, error) {
  312. return 0, errors.Trace(notSupported)
  313. }
  314. func (conn *ObfuscatedPacketConn) RemoteAddr() net.Addr {
  315. return conn.remoteAddr
  316. }
  317. // GetMetrics implements the common.MetricsSource interface.
  318. func (conn *ObfuscatedPacketConn) GetMetrics() common.LogFields {
  319. logFields := make(common.LogFields)
  320. // Include metrics, such as inproxy and fragmentor metrics, from the
  321. // underlying dial conn.
  322. underlyingMetrics, ok := conn.PacketConn.(common.MetricsSource)
  323. if ok {
  324. logFields.Add(underlyingMetrics.GetMetrics())
  325. }
  326. return logFields
  327. }
  328. func (conn *ObfuscatedPacketConn) readPacketWithType(
  329. p, oob []byte) (int, int, int, *net.UDPAddr, bool, error) {
  330. for {
  331. n, oobn, flags, addr, isIETF, err := conn.readPacket(p, oob)
  332. // Use the remoteAddr specified in NewClientObfuscatedPacketConn when
  333. // the underlying ReadFrom does not return a remote addr. This is the
  334. // case with inproxy.ClientConn.
  335. if addr == nil {
  336. addr = conn.remoteAddr
  337. }
  338. // When enabled, and when a packet is received, sometimes immediately
  339. // respond with a decoy packet, which is entirely random. Sending a
  340. // small number of these packets early in the connection is intended
  341. // to frustrate simple traffic fingerprinting which looks for a
  342. // certain number of packets client->server, followed by a certain
  343. // number of packets server->client, and so on.
  344. //
  345. // TODO: use a more sophisticated distribution; configure via tactics
  346. // parameters; add server-side decoy packet injection.
  347. //
  348. // See also:
  349. //
  350. // Tor Project's Sharknado concept:
  351. // https://gitlab.torproject.org/legacy/trac/-/issues/30716#note_2326086
  352. //
  353. // Lantern's OQUIC specification:
  354. // https://github.com/getlantern/quicwrapper/blob/master/OQUIC.md
  355. if err == nil && conn.isIETFClient && conn.isDecoyClient {
  356. count := atomic.LoadInt32(&conn.decoyPacketCount)
  357. if count > 0 && conn.paddingPRNG.FlipCoin() {
  358. if atomic.CompareAndSwapInt32(&conn.decoyPacketCount, count, count-1) {
  359. packetSize := conn.paddingPRNG.Range(
  360. 1, getMaxPreDiscoveryPacketSize(addr))
  361. // decoyBuffer is all zeros, so the QUIC Fixed Bit is zero.
  362. // Ignore any errors when writing decoy packets.
  363. _, _ = conn.WriteTo(conn.decoyBuffer[:packetSize], addr)
  364. }
  365. }
  366. }
  367. // Ignore/drop packets with an invalid QUIC Fixed Bit (see RFC 9000,
  368. // Packet Formats).
  369. if err == nil && (isIETF || conn.isIETFClient) && n > 0 && (p[0]&0x40) == 0 {
  370. continue
  371. }
  372. // Do not wrap any I/O err returned by conn.PacketConn
  373. return n, oobn, flags, addr, isIETF, err
  374. }
  375. }
  376. func (conn *ObfuscatedPacketConn) readPacket(
  377. p, oob []byte) (int, int, int, *net.UDPAddr, bool, error) {
  378. var n, oobn, flags int
  379. var addr *net.UDPAddr
  380. var err error
  381. oobCapablePacketConn, ok := conn.PacketConn.(ietf_quic.OOBCapablePacketConn)
  382. if ok {
  383. // Read OOB ECN bits when supported by the packet conn.
  384. n, oobn, flags, addr, err = oobCapablePacketConn.ReadMsgUDP(p, oob)
  385. } else {
  386. // Fall back to a generic ReadFrom, supported by any packet conn.
  387. var netAddr net.Addr
  388. n, netAddr, err = conn.PacketConn.ReadFrom(p)
  389. if netAddr != nil {
  390. // Directly convert from net.Addr to *net.UDPAddr, if possible.
  391. addr, ok = netAddr.(*net.UDPAddr)
  392. if !ok {
  393. addr, err = net.ResolveUDPAddr("udp", netAddr.String())
  394. }
  395. }
  396. }
  397. // Data is processed even when err != nil, as ReadFrom may return both
  398. // a packet and an error, such as io.EOF.
  399. // See: https://golang.org/pkg/net/#PacketConn.
  400. // In client mode, obfuscation is always performed as the client knows it is
  401. // using obfuscation. In server mode, DPI is performed to distinguish whether
  402. // the QUIC packet for a new flow is obfuscated or not, and whether it's IETF
  403. // or gQUIC. The isIETF return value is set only in server mode and is set
  404. // only when the function returns no error.
  405. isObfuscated := true
  406. isIETF := true
  407. var address string
  408. var firstFlowPacket bool
  409. var lastPacketTime time.Time
  410. if n > 0 {
  411. if conn.isServer {
  412. // The server handles both plain and obfuscated QUIC packets.
  413. // isQUIC performs DPI to determine whether the packet appears to
  414. // be QUIC, in which case deobfuscation is not performed. Not all
  415. // plain QUIC packets will pass the DPI test, but the initial
  416. // packet(s) in a flow are expected to match; so the server
  417. // records a peer "mode", referenced by peer address to know when
  418. // to skip deobfuscation for later packets.
  419. //
  420. // It's possible for clients to redial QUIC connections,
  421. // transitioning from obfuscated to plain, using the same source
  422. // address (IP and port). This is more likely when many clients
  423. // are behind NAT. If a packet appears to be QUIC, this will reset
  424. // any existing peer "mode" to plain. The obfuscator checks that
  425. // its obfuscated packets don't pass the QUIC DPI test.
  426. //
  427. // TODO: delete peerMode when a packet is a client connection
  428. // termination QUIC packet? Will reclaim peerMode memory faster
  429. // than relying on reaper.
  430. lastPacketTime = time.Now()
  431. // isIETF is not meaningful if not the first packet in a flow and is not
  432. // meaningful when first packet is obfuscated. To correctly indicate isIETF
  433. // when obfuscated, the isIETFQUICClientHello test is repeated after
  434. // deobfuscating the packet.
  435. var isQUIC bool
  436. isQUIC, isIETF = isQUICClientHello(p[:n])
  437. isObfuscated = !isQUIC
  438. if isObfuscated && isIETF {
  439. return n, oobn, flags, addr, false, newTemporaryNetError(
  440. errors.Tracef("unexpected isQUIC result"))
  441. }
  442. // Without addr, the mode cannot be determined.
  443. if addr == nil {
  444. return n, oobn, flags, addr, true, newTemporaryNetError(
  445. errors.Tracef("missing addr"))
  446. }
  447. conn.peerModesMutex.Lock()
  448. address = addr.String()
  449. mode, ok := conn.peerModes[address]
  450. if !ok {
  451. // This is a new flow.
  452. // See concurrent writer limit comment in writePacket.
  453. concurrentWriters := atomic.LoadInt32(&conn.concurrentWriters)
  454. if concurrentWriters > CONCURRENT_WRITER_LIMIT {
  455. conn.peerModesMutex.Unlock()
  456. return 0, 0, 0, nil, true, newTemporaryNetError(errors.TraceNew("too many concurrent writers"))
  457. }
  458. mode = &peerMode{isObfuscated: isObfuscated, isIETF: isIETF}
  459. conn.peerModes[address] = mode
  460. firstFlowPacket = true
  461. } else if mode.isStale() ||
  462. (isQUIC && (mode.isObfuscated || (mode.isIETF != isIETF))) {
  463. // The address for this flow has been seen before, but either (1) it's
  464. // stale and not yet reaped; or (2) the client has redialed and switched
  465. // from obfuscated to non-obfuscated; or (3) the client has redialed and
  466. // switched non-obfuscated gQUIC<-->IETF. These cases are treated like a
  467. // new flow.
  468. //
  469. // Limitation: since the DPI doesn't detect QUIC in post-Hello
  470. // non-obfuscated packets, some client redial cases are not identified as
  471. // and handled like new flows and the QUIC session will fail. These cases
  472. // include the client immediately redialing and switching from
  473. // non-obfuscated to obfuscated or switching obfuscated gQUIC<-->IETF.
  474. mode.isObfuscated = isObfuscated
  475. mode.isIETF = isIETF
  476. firstFlowPacket = true
  477. } else {
  478. isObfuscated = mode.isObfuscated
  479. isIETF = mode.isIETF
  480. }
  481. mode.lastPacketTime = lastPacketTime
  482. isIETF = mode.isIETF
  483. conn.peerModesMutex.Unlock()
  484. } else {
  485. isIETF = conn.isIETFClient
  486. }
  487. if isObfuscated {
  488. // We can use p as a scratch buffer for deobfuscation, and this
  489. // avoids allocting a buffer.
  490. if n < (NONCE_SIZE + 1) {
  491. return n, oobn, flags, addr, true, newTemporaryNetError(
  492. errors.Tracef("unexpected obfuscated QUIC packet length: %d", n))
  493. }
  494. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], p[0:NONCE_SIZE])
  495. if err != nil {
  496. return n, oobn, flags, addr, true, errors.Trace(err)
  497. }
  498. cipher.XORKeyStream(p[NONCE_SIZE:], p[NONCE_SIZE:])
  499. // The padding length check allows legacy gQUIC padding to exceed
  500. // its 64 byte maximum, as we don't yet know if this is gQUIC or
  501. // IETF QUIC.
  502. paddingLen := int(p[NONCE_SIZE])
  503. if paddingLen > MAX_PADDING_SIZE || paddingLen > n-(NONCE_SIZE+1) {
  504. return n, oobn, flags, addr, true, newTemporaryNetError(
  505. errors.Tracef("unexpected padding length: %d, %d", paddingLen, n))
  506. }
  507. n -= (NONCE_SIZE + 1) + paddingLen
  508. copy(p[0:n], p[(NONCE_SIZE+1)+paddingLen:n+(NONCE_SIZE+1)+paddingLen])
  509. if conn.isServer && firstFlowPacket {
  510. isIETF = isIETFQUICClientHello(p[0:n])
  511. // When an obfuscated packet looks like neither IETF nor
  512. // gQUIC, force it through the IETF code path which will
  513. // perform anti-probing check before sending any response
  514. // packet. The gQUIC stack may respond with a version
  515. // negotiation packet.
  516. //
  517. // Ensure that mode.isIETF is set to true before returning,
  518. // so subsequent packets in the same flow are also forced
  519. // through the same anti-probing code path.
  520. //
  521. // Limitation: the following race condition check is not
  522. // consistent with this constraint. This will be resolved by
  523. // disabling gQUIC or once gQUIC is ultimatel retired.
  524. if !isIETF && !isGQUICClientHello(p[0:n]) {
  525. isIETF = true
  526. }
  527. conn.peerModesMutex.Lock()
  528. mode, ok := conn.peerModes[address]
  529. // There's a possible race condition between the two instances of locking
  530. // peerModesMutex: the client might redial in the meantime. Check that the
  531. // mode state is unchanged from when the lock was last held.
  532. if !ok || mode.isObfuscated != true || mode.isIETF != false ||
  533. mode.lastPacketTime != lastPacketTime {
  534. conn.peerModesMutex.Unlock()
  535. return n, oobn, flags, addr, true, newTemporaryNetError(
  536. errors.Tracef("unexpected peer mode"))
  537. }
  538. mode.isIETF = isIETF
  539. conn.peerModesMutex.Unlock()
  540. // Enforce the MIN_INITIAL_PACKET_SIZE size requirement for new flows.
  541. //
  542. // Limitations:
  543. //
  544. // - The Initial packet may be sent more than once, but we
  545. // only check the very first packet.
  546. // - For session resumption, the first packet may be a
  547. // Handshake packet, not an Initial packet, and can be smaller.
  548. if isIETF && n < MIN_INITIAL_PACKET_SIZE {
  549. return n, oobn, flags, addr, true, newTemporaryNetError(errors.Tracef(
  550. "unexpected first QUIC packet length: %d", n))
  551. }
  552. }
  553. }
  554. }
  555. // Do not wrap any I/O err returned by conn.PacketConn
  556. return n, oobn, flags, addr, isIETF, err
  557. }
  558. type obfuscatorBuffer struct {
  559. buffer [MAX_PACKET_SIZE]byte
  560. }
  561. var obfuscatorBufferPool = &sync.Pool{
  562. New: func() interface{} {
  563. return new(obfuscatorBuffer)
  564. },
  565. }
  566. func (conn *ObfuscatedPacketConn) writePacket(
  567. p, oob []byte, addr *net.UDPAddr) (int, int, error) {
  568. n := len(p)
  569. isObfuscated := true
  570. isIETF := true
  571. if conn.isServer {
  572. // Drop packets when there are too many concurrent writers.
  573. //
  574. // Typically, a UDP socket write will complete in microseconds, and
  575. // the socket write buffer should rarely fill up. However, Go's
  576. // runtime will loop indefinitely on EAGAIN, the error returned when
  577. // a UDP socket write buffer is full. Additionally, Go's runtime
  578. // serializes socket writes, so once a write blocks, all concurrent
  579. // writes also block.
  580. //
  581. // The EAGAIN condition may arise due to problems with the host's
  582. // driver or NIC, among other network issues on the host. We have
  583. // observed that, on such problematic hosts, quic-go ends up with an
  584. // unbounded number of goroutines blocking on UDP socket writes,
  585. // almost all trying to send a final packet when closing a
  586. // connection, due to handshake timeout. This condition leads to
  587. // excess memory usage on the host and triggers load limiting with
  588. // few connected clients.
  589. //
  590. // To avoid this condition, drop write packets, without calling the
  591. // socket write, once there is an excess number of concurrent
  592. // writers, presumably all blocked due to EAGAIN. Use a high enough
  593. // limit to avoid dropping packets on a busy, healthy host -- there
  594. // will always be some number of concurrent writers, since the QUIC
  595. // server uses a single socket for all writes.
  596. //
  597. // The concurrent writer limit is also checked in readPacket and used
  598. // to drop packets from new flows, to avoid starting new QUIC
  599. // connection handshakes while writes are blocked.
  600. //
  601. // The WriteTimeoutUDPConn is not used in the server case. While it is
  602. // effective at interrupting EAGAIN blocking on the client, its use
  603. // of SetWriteDeadline will extend the deadline for all blocked
  604. // writers, which fails to clear the server-side backlog.
  605. concurrentWriters := atomic.AddInt32(&conn.concurrentWriters, 1)
  606. defer atomic.AddInt32(&conn.concurrentWriters, -1)
  607. if concurrentWriters > CONCURRENT_WRITER_LIMIT {
  608. return 0, 0, newTemporaryNetError(errors.TraceNew("too many concurrent writers"))
  609. }
  610. conn.peerModesMutex.Lock()
  611. address := addr.String()
  612. mode, ok := conn.peerModes[address]
  613. if ok {
  614. isObfuscated = mode.isObfuscated
  615. isIETF = mode.isIETF
  616. }
  617. conn.peerModesMutex.Unlock()
  618. } else {
  619. isIETF = conn.isIETFClient
  620. }
  621. if isObfuscated {
  622. if n > MAX_PACKET_SIZE {
  623. return 0, 0, newTemporaryNetError(errors.Tracef(
  624. "unexpected QUIC packet length: %d", n))
  625. }
  626. // Note: escape analysis showed a local array escaping to the heap,
  627. // so use a buffer pool instead to avoid heap allocation per packet.
  628. b := obfuscatorBufferPool.Get().(*obfuscatorBuffer)
  629. buffer := b.buffer[:]
  630. defer obfuscatorBufferPool.Put(b)
  631. for {
  632. // Note: this zero-memory pattern is compiler optimized:
  633. // https://golang.org/cl/137880043
  634. for i := range buffer {
  635. buffer[i] = 0
  636. }
  637. nonce := buffer[0:NONCE_SIZE]
  638. conn.noncePRNG.Read(nonce)
  639. // This transform may reduce the entropy of the nonce, which increases
  640. // the chance of nonce reuse. However, this chacha20 encryption is for
  641. // obfuscation purposes only.
  642. if conn.nonceTransformerParameters != nil {
  643. err := conn.nonceTransformerParameters.Apply(nonce)
  644. if err != nil {
  645. return 0, 0, errors.Trace(err)
  646. }
  647. }
  648. maxPadding := getMaxPaddingSize(isIETF, addr, n)
  649. paddingLen := conn.paddingPRNG.Intn(maxPadding + 1)
  650. buffer[NONCE_SIZE] = uint8(paddingLen)
  651. padding := buffer[(NONCE_SIZE + 1) : (NONCE_SIZE+1)+paddingLen]
  652. conn.paddingPRNG.Read(padding)
  653. copy(buffer[(NONCE_SIZE+1)+paddingLen:], p)
  654. dataLen := (NONCE_SIZE + 1) + paddingLen + n
  655. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], nonce)
  656. if err != nil {
  657. return 0, 0, errors.Trace(err)
  658. }
  659. packet := buffer[NONCE_SIZE:dataLen]
  660. cipher.XORKeyStream(packet, packet)
  661. p = buffer[:dataLen]
  662. // Don't use obfuscation that looks like QUIC, or the
  663. // peer will not treat this packet as obfuscated.
  664. isQUIC, _ := isQUICClientHello(p)
  665. if !isQUIC {
  666. break
  667. }
  668. }
  669. }
  670. var oobn int
  671. var err error
  672. oobCapablePacketConn, ok := conn.PacketConn.(ietf_quic.OOBCapablePacketConn)
  673. if ok {
  674. // Write OOB bits if supported by the packet conn.
  675. //
  676. // At this time, quic-go reads but does not write ECN OOB bits. On the
  677. // client-side, the Dial function arranges for conn.PacketConn to not
  678. // implement OOBCapablePacketConn when using obfuscated QUIC, and so
  679. // quic-go is not expected to write ECN bits -- a potential
  680. // obfuscation fingerprint -- in the future, on the client-side.
  681. //
  682. // Limitation: on the server-side, the single UDP server socket is
  683. // wrapped with ObfuscatedPacketConn and supports both obfuscated and
  684. // regular QUIC; as it stands, this logic will support writing ECN
  685. // bits for both obfuscated and regular QUIC.
  686. _, oobn, err = oobCapablePacketConn.WriteMsgUDP(p, oob, addr)
  687. } else {
  688. // Fall back to WriteTo, supported by any packet conn. If there are
  689. // OOB bits to be written, fail.
  690. if oob != nil {
  691. return 0, 0, errors.TraceNew("unexpected OOB payload for non-OOBCapablePacketConn")
  692. }
  693. _, err = conn.PacketConn.WriteTo(p, addr)
  694. }
  695. // Return n = len(input p) bytes written even when p is an obfuscated
  696. // buffer and longer than the input p.
  697. // Do not wrap any I/O err returned by conn.PacketConn
  698. return n, oobn, err
  699. }
  700. func getMaxPreDiscoveryPacketSize(addr net.Addr) int {
  701. maxPacketSize := MAX_PRE_DISCOVERY_PACKET_SIZE_IPV4
  702. if udpAddr, ok := addr.(*net.UDPAddr); ok &&
  703. udpAddr != nil && udpAddr.IP != nil && udpAddr.IP.To4() == nil {
  704. maxPacketSize = MAX_PRE_DISCOVERY_PACKET_SIZE_IPV6
  705. }
  706. return maxPacketSize
  707. }
  708. func getMaxPaddingSize(isIETF bool, addr net.Addr, packetSize int) int {
  709. maxPacketSize := getMaxPreDiscoveryPacketSize(addr)
  710. maxPadding := 0
  711. if isIETF {
  712. // quic-go starts with a maximum packet size of 1280, which is the
  713. // IPv6 minimum MTU as well as very commonly supported for IPv4
  714. // (quic-go may increase the maximum packet size via MTU discovery).
  715. // Do not pad beyond that initial maximum size. As a result, padding
  716. // is only added for smaller packets.
  717. // OBFUSCATED_PACKET_SIZE_ADJUSTMENT is already factored in via
  718. // Client/ServerInitalPacketPaddingAdjustment.
  719. maxPadding = maxPacketSize - packetSize
  720. if maxPadding < 0 {
  721. maxPadding = 0
  722. }
  723. if maxPadding > MAX_PADDING_SIZE {
  724. maxPadding = MAX_PADDING_SIZE
  725. }
  726. } else {
  727. // Legacy gQUIC has a strict maximum packet size of 1280, and legacy
  728. // obfuscation adds padding on top of that.
  729. maxPadding = (maxPacketSize + NONCE_SIZE + 1 + MAX_GQUIC_PADDING_SIZE) - packetSize
  730. if maxPadding < 0 {
  731. maxPadding = 0
  732. }
  733. if maxPadding > MAX_GQUIC_PADDING_SIZE {
  734. maxPadding = MAX_GQUIC_PADDING_SIZE
  735. }
  736. }
  737. return maxPadding
  738. }
  739. func (conn *ObfuscatedPacketConn) serverMaxPacketSizeAdjustment(
  740. addr net.Addr) int {
  741. if !conn.isServer {
  742. return 0
  743. }
  744. conn.peerModesMutex.Lock()
  745. address := addr.String()
  746. mode, ok := conn.peerModes[address]
  747. isObfuscated := ok && mode.isObfuscated
  748. conn.peerModesMutex.Unlock()
  749. if isObfuscated {
  750. return OBFUSCATED_MAX_PACKET_SIZE_ADJUSTMENT
  751. }
  752. return 0
  753. }
  754. func isQUICClientHello(buffer []byte) (bool, bool) {
  755. // As this function is called for every packet, it needs to be fast.
  756. //
  757. // As QUIC header parsing is complex, with many cases, we are not
  758. // presently doing that, although this might improve accuracy as we should
  759. // be able to identify the precise offset of indicators based on header
  760. // values.
  761. if isIETFQUICClientHello(buffer) {
  762. return true, true
  763. } else if isGQUICClientHello(buffer) {
  764. return true, false
  765. }
  766. return false, false
  767. }
  768. func isGQUICClientHello(buffer []byte) bool {
  769. // In all currently supported versions, the first client packet contains
  770. // the "CHLO" tag at one of the following offsets. The offset can vary for
  771. // a single version.
  772. //
  773. // Note that v44 does not include the "QUIC version" header field in its
  774. // first client packet.
  775. if (len(buffer) >= 33 &&
  776. buffer[29] == 'C' &&
  777. buffer[30] == 'H' &&
  778. buffer[31] == 'L' &&
  779. buffer[32] == 'O') ||
  780. (len(buffer) >= 35 &&
  781. buffer[31] == 'C' &&
  782. buffer[32] == 'H' &&
  783. buffer[33] == 'L' &&
  784. buffer[34] == 'O') ||
  785. (len(buffer) >= 38 &&
  786. buffer[34] == 'C' &&
  787. buffer[35] == 'H' &&
  788. buffer[36] == 'L' &&
  789. buffer[37] == 'O') {
  790. return true
  791. }
  792. return false
  793. }
  794. func isIETFQUICClientHello(buffer []byte) bool {
  795. // https://tools.ietf.org/html/draft-ietf-quic-transport-23#section-17.2:
  796. //
  797. // Check 1st nibble of byte 0:
  798. // 1... .... = Header Form: Long Header (1)
  799. // .1.. .... = Fixed Bit: True
  800. // ..00 .... = Packet Type: Initial (0)
  801. //
  802. // Then check bytes 1..4 for expected version number.
  803. if len(buffer) < 5 {
  804. return false
  805. }
  806. if buffer[0]>>4 != 0x0c {
  807. return false
  808. }
  809. // IETF QUIC version 1, RFC 9000
  810. return buffer[1] == 0 &&
  811. buffer[2] == 0 &&
  812. buffer[3] == 0 &&
  813. buffer[4] == 0x1
  814. }