obfuscator.go 34 KB

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