obfuscator.go 29 KB

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