obfuscator.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. }
  480. mode.lastPacketTime = lastPacketTime
  481. isIETF = mode.isIETF
  482. conn.peerModesMutex.Unlock()
  483. } else {
  484. isIETF = conn.isIETFClient
  485. }
  486. if isObfuscated {
  487. // We can use p as a scratch buffer for deobfuscation, and this
  488. // avoids allocting a buffer.
  489. if n < (NONCE_SIZE + 1) {
  490. return n, oobn, flags, addr, true, newTemporaryNetError(
  491. errors.Tracef("unexpected obfuscated QUIC packet length: %d", n))
  492. }
  493. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], p[0:NONCE_SIZE])
  494. if err != nil {
  495. return n, oobn, flags, addr, true, errors.Trace(err)
  496. }
  497. cipher.XORKeyStream(p[NONCE_SIZE:], p[NONCE_SIZE:])
  498. // The padding length check allows legacy gQUIC padding to exceed
  499. // its 64 byte maximum, as we don't yet know if this is gQUIC or
  500. // IETF QUIC.
  501. paddingLen := int(p[NONCE_SIZE])
  502. if paddingLen > MAX_PADDING_SIZE || paddingLen > n-(NONCE_SIZE+1) {
  503. return n, oobn, flags, addr, true, newTemporaryNetError(
  504. errors.Tracef("unexpected padding length: %d, %d", paddingLen, n))
  505. }
  506. n -= (NONCE_SIZE + 1) + paddingLen
  507. copy(p[0:n], p[(NONCE_SIZE+1)+paddingLen:n+(NONCE_SIZE+1)+paddingLen])
  508. if conn.isServer && firstFlowPacket {
  509. isIETF = isIETFQUICClientHello(p[0:n])
  510. // When an obfuscated packet looks like neither IETF nor
  511. // gQUIC, force it through the IETF code path which will
  512. // perform anti-probing check before sending any response
  513. // packet. The gQUIC stack may respond with a version
  514. // negotiation packet.
  515. //
  516. // Ensure that mode.isIETF is set to true before returning,
  517. // so subsequent packets in the same flow are also forced
  518. // through the same anti-probing code path.
  519. //
  520. // Limitation: the following race condition check is not
  521. // consistent with this constraint. This will be resolved by
  522. // disabling gQUIC or once gQUIC is ultimatel retired.
  523. if !isIETF && !isGQUICClientHello(p[0:n]) {
  524. isIETF = true
  525. }
  526. conn.peerModesMutex.Lock()
  527. mode, ok := conn.peerModes[address]
  528. // There's a possible race condition between the two instances of locking
  529. // peerModesMutex: the client might redial in the meantime. Check that the
  530. // mode state is unchanged from when the lock was last held.
  531. if !ok || !mode.isObfuscated || mode.isIETF ||
  532. mode.lastPacketTime != lastPacketTime {
  533. conn.peerModesMutex.Unlock()
  534. return n, oobn, flags, addr, true, newTemporaryNetError(
  535. errors.Tracef("unexpected peer mode"))
  536. }
  537. mode.isIETF = isIETF
  538. conn.peerModesMutex.Unlock()
  539. // Enforce the MIN_INITIAL_PACKET_SIZE size requirement for new flows.
  540. //
  541. // Limitations:
  542. //
  543. // - The Initial packet may be sent more than once, but we
  544. // only check the very first packet.
  545. // - For session resumption, the first packet may be a
  546. // Handshake packet, not an Initial packet, and can be smaller.
  547. if isIETF && n < MIN_INITIAL_PACKET_SIZE {
  548. return n, oobn, flags, addr, true, newTemporaryNetError(errors.Tracef(
  549. "unexpected first QUIC packet length: %d", n))
  550. }
  551. }
  552. }
  553. }
  554. // Do not wrap any I/O err returned by conn.PacketConn
  555. return n, oobn, flags, addr, isIETF, err
  556. }
  557. type obfuscatorBuffer struct {
  558. buffer [MAX_PACKET_SIZE]byte
  559. }
  560. var obfuscatorBufferPool = &sync.Pool{
  561. New: func() interface{} {
  562. return new(obfuscatorBuffer)
  563. },
  564. }
  565. func (conn *ObfuscatedPacketConn) writePacket(
  566. p, oob []byte, addr *net.UDPAddr) (int, int, error) {
  567. n := len(p)
  568. isObfuscated := true
  569. isIETF := true
  570. if conn.isServer {
  571. // Drop packets when there are too many concurrent writers.
  572. //
  573. // Typically, a UDP socket write will complete in microseconds, and
  574. // the socket write buffer should rarely fill up. However, Go's
  575. // runtime will loop indefinitely on EAGAIN, the error returned when
  576. // a UDP socket write buffer is full. Additionally, Go's runtime
  577. // serializes socket writes, so once a write blocks, all concurrent
  578. // writes also block.
  579. //
  580. // The EAGAIN condition may arise due to problems with the host's
  581. // driver or NIC, among other network issues on the host. We have
  582. // observed that, on such problematic hosts, quic-go ends up with an
  583. // unbounded number of goroutines blocking on UDP socket writes,
  584. // almost all trying to send a final packet when closing a
  585. // connection, due to handshake timeout. This condition leads to
  586. // excess memory usage on the host and triggers load limiting with
  587. // few connected clients.
  588. //
  589. // To avoid this condition, drop write packets, without calling the
  590. // socket write, once there is an excess number of concurrent
  591. // writers, presumably all blocked due to EAGAIN. Use a high enough
  592. // limit to avoid dropping packets on a busy, healthy host -- there
  593. // will always be some number of concurrent writers, since the QUIC
  594. // server uses a single socket for all writes.
  595. //
  596. // The concurrent writer limit is also checked in readPacket and used
  597. // to drop packets from new flows, to avoid starting new QUIC
  598. // connection handshakes while writes are blocked.
  599. //
  600. // The WriteTimeoutUDPConn is not used in the server case. While it is
  601. // effective at interrupting EAGAIN blocking on the client, its use
  602. // of SetWriteDeadline will extend the deadline for all blocked
  603. // writers, which fails to clear the server-side backlog.
  604. concurrentWriters := atomic.AddInt32(&conn.concurrentWriters, 1)
  605. defer atomic.AddInt32(&conn.concurrentWriters, -1)
  606. if concurrentWriters > CONCURRENT_WRITER_LIMIT {
  607. return 0, 0, newTemporaryNetError(errors.TraceNew("too many concurrent writers"))
  608. }
  609. conn.peerModesMutex.Lock()
  610. address := addr.String()
  611. mode, ok := conn.peerModes[address]
  612. if ok {
  613. isObfuscated = mode.isObfuscated
  614. isIETF = mode.isIETF
  615. }
  616. conn.peerModesMutex.Unlock()
  617. } else {
  618. isIETF = conn.isIETFClient
  619. }
  620. if isObfuscated {
  621. if n > MAX_PACKET_SIZE {
  622. return 0, 0, newTemporaryNetError(errors.Tracef(
  623. "unexpected QUIC packet length: %d", n))
  624. }
  625. // Note: escape analysis showed a local array escaping to the heap,
  626. // so use a buffer pool instead to avoid heap allocation per packet.
  627. b := obfuscatorBufferPool.Get().(*obfuscatorBuffer)
  628. buffer := b.buffer[:]
  629. defer obfuscatorBufferPool.Put(b)
  630. for {
  631. // Note: this zero-memory pattern is compiler optimized:
  632. // https://golang.org/cl/137880043
  633. for i := range buffer {
  634. buffer[i] = 0
  635. }
  636. nonce := buffer[0:NONCE_SIZE]
  637. _, _ = conn.noncePRNG.Read(nonce)
  638. // This transform may reduce the entropy of the nonce, which increases
  639. // the chance of nonce reuse. However, this chacha20 encryption is for
  640. // obfuscation purposes only.
  641. if conn.nonceTransformerParameters != nil {
  642. err := conn.nonceTransformerParameters.Apply(nonce)
  643. if err != nil {
  644. return 0, 0, errors.Trace(err)
  645. }
  646. }
  647. maxPadding := getMaxPaddingSize(isIETF, addr, n)
  648. paddingLen := conn.paddingPRNG.Intn(maxPadding + 1)
  649. buffer[NONCE_SIZE] = uint8(paddingLen)
  650. padding := buffer[(NONCE_SIZE + 1) : (NONCE_SIZE+1)+paddingLen]
  651. _, _ = conn.paddingPRNG.Read(padding)
  652. copy(buffer[(NONCE_SIZE+1)+paddingLen:], p)
  653. dataLen := (NONCE_SIZE + 1) + paddingLen + n
  654. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], nonce)
  655. if err != nil {
  656. return 0, 0, errors.Trace(err)
  657. }
  658. packet := buffer[NONCE_SIZE:dataLen]
  659. cipher.XORKeyStream(packet, packet)
  660. p = buffer[:dataLen]
  661. // Don't use obfuscation that looks like QUIC, or the
  662. // peer will not treat this packet as obfuscated.
  663. isQUIC, _ := isQUICClientHello(p)
  664. if !isQUIC {
  665. break
  666. }
  667. }
  668. }
  669. var oobn int
  670. var err error
  671. oobCapablePacketConn, ok := conn.PacketConn.(ietf_quic.OOBCapablePacketConn)
  672. if ok {
  673. // Write OOB bits if supported by the packet conn.
  674. //
  675. // At this time, quic-go reads but does not write ECN OOB bits. On the
  676. // client-side, the Dial function arranges for conn.PacketConn to not
  677. // implement OOBCapablePacketConn when using obfuscated QUIC, and so
  678. // quic-go is not expected to write ECN bits -- a potential
  679. // obfuscation fingerprint -- in the future, on the client-side.
  680. //
  681. // Limitation: on the server-side, the single UDP server socket is
  682. // wrapped with ObfuscatedPacketConn and supports both obfuscated and
  683. // regular QUIC; as it stands, this logic will support writing ECN
  684. // bits for both obfuscated and regular QUIC.
  685. _, oobn, err = oobCapablePacketConn.WriteMsgUDP(p, oob, addr)
  686. } else {
  687. // Fall back to WriteTo, supported by any packet conn. If there are
  688. // OOB bits to be written, fail.
  689. if oob != nil {
  690. return 0, 0, errors.TraceNew("unexpected OOB payload for non-OOBCapablePacketConn")
  691. }
  692. _, err = conn.PacketConn.WriteTo(p, addr)
  693. }
  694. // Return n = len(input p) bytes written even when p is an obfuscated
  695. // buffer and longer than the input p.
  696. // Do not wrap any I/O err returned by conn.PacketConn
  697. return n, oobn, err
  698. }
  699. func getMaxPreDiscoveryPacketSize(addr net.Addr) int {
  700. maxPacketSize := MAX_PRE_DISCOVERY_PACKET_SIZE_IPV4
  701. if udpAddr, ok := addr.(*net.UDPAddr); ok &&
  702. udpAddr != nil && udpAddr.IP != nil && udpAddr.IP.To4() == nil {
  703. maxPacketSize = MAX_PRE_DISCOVERY_PACKET_SIZE_IPV6
  704. }
  705. return maxPacketSize
  706. }
  707. func getMaxPaddingSize(isIETF bool, addr net.Addr, packetSize int) int {
  708. maxPacketSize := getMaxPreDiscoveryPacketSize(addr)
  709. maxPadding := 0
  710. if isIETF {
  711. // quic-go starts with a maximum packet size of 1280, which is the
  712. // IPv6 minimum MTU as well as very commonly supported for IPv4
  713. // (quic-go may increase the maximum packet size via MTU discovery).
  714. // Do not pad beyond that initial maximum size. As a result, padding
  715. // is only added for smaller packets.
  716. // OBFUSCATED_PACKET_SIZE_ADJUSTMENT is already factored in via
  717. // Client/ServerInitalPacketPaddingAdjustment.
  718. maxPadding = maxPacketSize - packetSize
  719. if maxPadding < 0 {
  720. maxPadding = 0
  721. }
  722. if maxPadding > MAX_PADDING_SIZE {
  723. maxPadding = MAX_PADDING_SIZE
  724. }
  725. } else {
  726. // Legacy gQUIC has a strict maximum packet size of 1280, and legacy
  727. // obfuscation adds padding on top of that.
  728. maxPadding = (maxPacketSize + NONCE_SIZE + 1 + MAX_GQUIC_PADDING_SIZE) - packetSize
  729. if maxPadding < 0 {
  730. maxPadding = 0
  731. }
  732. if maxPadding > MAX_GQUIC_PADDING_SIZE {
  733. maxPadding = MAX_GQUIC_PADDING_SIZE
  734. }
  735. }
  736. return maxPadding
  737. }
  738. func (conn *ObfuscatedPacketConn) serverMaxPacketSizeAdjustment(
  739. addr net.Addr) int {
  740. if !conn.isServer {
  741. return 0
  742. }
  743. conn.peerModesMutex.Lock()
  744. address := addr.String()
  745. mode, ok := conn.peerModes[address]
  746. isObfuscated := ok && mode.isObfuscated
  747. conn.peerModesMutex.Unlock()
  748. if isObfuscated {
  749. return OBFUSCATED_MAX_PACKET_SIZE_ADJUSTMENT
  750. }
  751. return 0
  752. }
  753. func isQUICClientHello(buffer []byte) (bool, bool) {
  754. // As this function is called for every packet, it needs to be fast.
  755. //
  756. // As QUIC header parsing is complex, with many cases, we are not
  757. // presently doing that, although this might improve accuracy as we should
  758. // be able to identify the precise offset of indicators based on header
  759. // values.
  760. if isIETFQUICClientHello(buffer) {
  761. return true, true
  762. } else if isGQUICClientHello(buffer) {
  763. return true, false
  764. }
  765. return false, false
  766. }
  767. func isGQUICClientHello(buffer []byte) bool {
  768. // In all currently supported versions, the first client packet contains
  769. // the "CHLO" tag at one of the following offsets. The offset can vary for
  770. // a single version.
  771. //
  772. // Note that v44 does not include the "QUIC version" header field in its
  773. // first client packet.
  774. if (len(buffer) >= 33 &&
  775. buffer[29] == 'C' &&
  776. buffer[30] == 'H' &&
  777. buffer[31] == 'L' &&
  778. buffer[32] == 'O') ||
  779. (len(buffer) >= 35 &&
  780. buffer[31] == 'C' &&
  781. buffer[32] == 'H' &&
  782. buffer[33] == 'L' &&
  783. buffer[34] == 'O') ||
  784. (len(buffer) >= 38 &&
  785. buffer[34] == 'C' &&
  786. buffer[35] == 'H' &&
  787. buffer[36] == 'L' &&
  788. buffer[37] == 'O') {
  789. return true
  790. }
  791. return false
  792. }
  793. func isIETFQUICClientHello(buffer []byte) bool {
  794. // https://tools.ietf.org/html/draft-ietf-quic-transport-23#section-17.2:
  795. //
  796. // Check 1st nibble of byte 0:
  797. // 1... .... = Header Form: Long Header (1)
  798. // .1.. .... = Fixed Bit: True
  799. // ..00 .... = Packet Type: Initial (0)
  800. //
  801. // Then check bytes 1..4 for expected version number.
  802. if len(buffer) < 5 {
  803. return false
  804. }
  805. if buffer[0]>>4 != 0x0c {
  806. return false
  807. }
  808. // IETF QUIC version 1, RFC 9000
  809. return buffer[1] == 0 &&
  810. buffer[2] == 0 &&
  811. buffer[3] == 0 &&
  812. buffer[4] == 0x1
  813. }