obfuscator.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // +build !DISABLE_QUIC
  2. /*
  3. * Copyright (c) 2018, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package quic
  21. import (
  22. "crypto/sha256"
  23. "io"
  24. "net"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/Yawning/chacha20"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  31. "golang.org/x/crypto/hkdf"
  32. )
  33. const (
  34. MAX_QUIC_IPV4_PACKET_SIZE = 1252
  35. MAX_QUIC_IPV6_PACKET_SIZE = 1232
  36. MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE = 1372
  37. MAX_OBFUSCATED_QUIC_IPV6_PACKET_SIZE = 1352
  38. MAX_PADDING = 64
  39. NONCE_SIZE = 12
  40. RANDOM_STREAM_LIMIT = 1<<38 - 64
  41. )
  42. // ObfuscatedPacketConn wraps a QUIC net.PacketConn with an obfuscation layer
  43. // that obscures QUIC packets, adding random padding and producing uniformly
  44. // random payload.
  45. //
  46. // The crypto performed by ObfuscatedPacketConn is purely for obfuscation to
  47. // frusctrate wire-speed DPI and does not add privacy/security. The small
  48. // nonce space and single key per server is not cryptographically secure.
  49. //
  50. // A server-side ObfuscatedPacketConn performs simple QUIC DPI to distinguish
  51. // between obfuscated and non-obfsucated peer flows and responds accordingly.
  52. //
  53. // The header and padding added by ObfuscatedPacketConn on top of the QUIC
  54. // payload will increase UDP packets beyond the QUIC max of 1280 bytes,
  55. // introducing some risk of fragmentation and/or dropped packets.
  56. type ObfuscatedPacketConn struct {
  57. net.PacketConn
  58. isServer bool
  59. isClosed int32
  60. runWaitGroup *sync.WaitGroup
  61. stopBroadcast chan struct{}
  62. obfuscationKey [32]byte
  63. peerModesMutex sync.Mutex
  64. peerModes map[string]*peerMode
  65. noncePRNG *prng.PRNG
  66. paddingPRNG *prng.PRNG
  67. }
  68. type peerMode struct {
  69. isObfuscated bool
  70. isIETF bool
  71. lastPacketTime time.Time
  72. }
  73. func (p *peerMode) isStale() bool {
  74. return time.Since(p.lastPacketTime) >= SERVER_IDLE_TIMEOUT
  75. }
  76. // NewObfuscatedPacketConn creates a new ObfuscatedPacketConn.
  77. func NewObfuscatedPacketConn(
  78. conn net.PacketConn,
  79. isServer bool,
  80. obfuscationKey string,
  81. paddingSeed *prng.Seed) (*ObfuscatedPacketConn, error) {
  82. // There is no replay of obfuscation "encryption", just padding.
  83. nonceSeed, err := prng.NewSeed()
  84. if err != nil {
  85. return nil, errors.Trace(err)
  86. }
  87. packetConn := &ObfuscatedPacketConn{
  88. PacketConn: conn,
  89. isServer: isServer,
  90. peerModes: make(map[string]*peerMode),
  91. noncePRNG: prng.NewPRNGWithSeed(nonceSeed),
  92. paddingPRNG: prng.NewPRNGWithSeed(paddingSeed),
  93. }
  94. secret := []byte(obfuscationKey)
  95. salt := []byte("quic-obfuscation-key")
  96. _, err = io.ReadFull(
  97. hkdf.New(sha256.New, secret, salt, nil), packetConn.obfuscationKey[:])
  98. if err != nil {
  99. return nil, errors.Trace(err)
  100. }
  101. if isServer {
  102. packetConn.runWaitGroup = new(sync.WaitGroup)
  103. packetConn.stopBroadcast = make(chan struct{})
  104. // Reap stale peer mode information to reclaim memory.
  105. packetConn.runWaitGroup.Add(1)
  106. go func() {
  107. defer packetConn.runWaitGroup.Done()
  108. ticker := time.NewTicker(SERVER_IDLE_TIMEOUT / 2)
  109. defer ticker.Stop()
  110. for {
  111. select {
  112. case <-ticker.C:
  113. packetConn.peerModesMutex.Lock()
  114. for address, mode := range packetConn.peerModes {
  115. if mode.isStale() {
  116. delete(packetConn.peerModes, address)
  117. }
  118. }
  119. packetConn.peerModesMutex.Unlock()
  120. case <-packetConn.stopBroadcast:
  121. return
  122. }
  123. }
  124. }()
  125. }
  126. return packetConn, nil
  127. }
  128. func (conn *ObfuscatedPacketConn) Close() error {
  129. // Ensure close channel only called once.
  130. if !atomic.CompareAndSwapInt32(&conn.isClosed, 0, 1) {
  131. return nil
  132. }
  133. if conn.isServer {
  134. close(conn.stopBroadcast)
  135. conn.runWaitGroup.Wait()
  136. }
  137. return conn.PacketConn.Close()
  138. }
  139. type temporaryNetError struct {
  140. err error
  141. }
  142. func newTemporaryNetError(err error) *temporaryNetError {
  143. return &temporaryNetError{err: err}
  144. }
  145. func (e *temporaryNetError) Timeout() bool {
  146. return false
  147. }
  148. func (e *temporaryNetError) Temporary() bool {
  149. return true
  150. }
  151. func (e *temporaryNetError) Error() string {
  152. return e.err.Error()
  153. }
  154. func (conn *ObfuscatedPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
  155. n, addr, _, err := conn.readFromWithType(p)
  156. return n, addr, err
  157. }
  158. func (conn *ObfuscatedPacketConn) readFromWithType(p []byte) (int, net.Addr, bool, error) {
  159. n, addr, err := conn.PacketConn.ReadFrom(p)
  160. // Data is processed even when err != nil, as ReadFrom may return both
  161. // a packet and an error, such as io.EOF.
  162. // See: https://golang.org/pkg/net/#PacketConn.
  163. // In client mode, obfuscation is always performed as the client knows it is
  164. // using obfuscation. In server mode, DPI is performed to distinguish whether
  165. // the QUIC packet for a new flow is obfuscated or not, and whether it's IETF
  166. // or gQUIC. The isIETF return value is set only in server mode and is set
  167. // only when the function returns no error.
  168. isObfuscated := true
  169. var isIETF bool
  170. var address string
  171. var firstFlowPacket bool
  172. var lastPacketTime time.Time
  173. if n > 0 {
  174. if conn.isServer {
  175. // The server handles both plain and obfuscated QUIC packets.
  176. // isQUIC performs DPI to determine whether the packet appears to
  177. // be QUIC, in which case deobfuscation is not performed. Not all
  178. // plain QUIC packets will pass the DPI test, but the initial
  179. // packet(s) in a flow are expected to match; so the server
  180. // records a peer "mode", referenced by peer address to know when
  181. // to skip deobfuscation for later packets.
  182. //
  183. // It's possible for clients to redial QUIC connections,
  184. // transitioning from obfuscated to plain, using the same source
  185. // address (IP and port). This is more likely when many clients
  186. // are behind NAT. If a packet appears to be QUIC, this will reset
  187. // any existing peer "mode" to plain. The obfuscator checks that
  188. // its obfuscated packets don't pass the QUIC DPI test.
  189. //
  190. // TODO: delete peerMode when a packet is a client connection
  191. // termination QUIC packet? Will reclaim peerMode memory faster
  192. // than relying on reaper.
  193. lastPacketTime = time.Now()
  194. // isIETF is not meaningful if not the first packet in a flow and is not
  195. // meaningful when first packet is obfuscated. To correctly indicate isIETF
  196. // when obfuscated, the isIETFQUICClientHello test is repeated after
  197. // deobfuscating the packet.
  198. var isQUIC bool
  199. isQUIC, isIETF = isQUICClientHello(p[:n])
  200. isObfuscated = !isQUIC
  201. if isObfuscated && isIETF {
  202. return n, addr, false, newTemporaryNetError(
  203. errors.Tracef("unexpected isQUIC result"))
  204. }
  205. // Without addr, the mode cannot be determined.
  206. if addr == nil {
  207. return n, addr, false, newTemporaryNetError(errors.Tracef("missing addr"))
  208. }
  209. conn.peerModesMutex.Lock()
  210. address = addr.String()
  211. mode, ok := conn.peerModes[address]
  212. if !ok {
  213. // This is a new flow.
  214. mode = &peerMode{isObfuscated: isObfuscated, isIETF: isIETF}
  215. conn.peerModes[address] = mode
  216. firstFlowPacket = true
  217. } else if mode.isStale() ||
  218. (isQUIC && (mode.isObfuscated || (mode.isIETF != isIETF))) {
  219. // The address for this flow has been seen before, but either (1) it's
  220. // stale and not yet reaped; or (2) the client has redialed and switched
  221. // from obfuscated to non-obfuscated; or (3) the client has redialed and
  222. // switched non-obfuscated gQUIC<-->IETF. These cases are treated like a
  223. // new flow.
  224. //
  225. // Limitation: since the DPI doesn't detect QUIC in post-Hello
  226. // non-obfuscated packets, some client redial cases are not identified as
  227. // and handled like new flows and the QUIC session will fail. These cases
  228. // include the client immediately redialing and switching from
  229. // non-obfuscated to obfuscated or switching obfuscated gQUIC<-->IETF.
  230. mode.isObfuscated = isObfuscated
  231. mode.isIETF = isIETF
  232. firstFlowPacket = true
  233. } else {
  234. isObfuscated = mode.isObfuscated
  235. isIETF = mode.isIETF
  236. }
  237. mode.lastPacketTime = lastPacketTime
  238. isIETF = mode.isIETF
  239. conn.peerModesMutex.Unlock()
  240. }
  241. if isObfuscated {
  242. // We can use p as a scratch buffer for deobfuscation, and this
  243. // avoids allocting a buffer.
  244. if n < (NONCE_SIZE + 1) {
  245. return n, addr, false, newTemporaryNetError(errors.Tracef(
  246. "unexpected obfuscated QUIC packet length: %d", n))
  247. }
  248. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], p[0:NONCE_SIZE])
  249. if err != nil {
  250. return n, addr, false, errors.Trace(err)
  251. }
  252. cipher.XORKeyStream(p[NONCE_SIZE:], p[NONCE_SIZE:])
  253. paddingLen := int(p[NONCE_SIZE])
  254. if paddingLen > MAX_PADDING || paddingLen > n-(NONCE_SIZE+1) {
  255. return n, addr, false, newTemporaryNetError(errors.Tracef(
  256. "unexpected padding length: %d, %d", paddingLen, n))
  257. }
  258. n -= (NONCE_SIZE + 1) + paddingLen
  259. copy(p[0:n], p[(NONCE_SIZE+1)+paddingLen:n+(NONCE_SIZE+1)+paddingLen])
  260. if conn.isServer && firstFlowPacket {
  261. isIETF = isIETFQUICClientHello(p[0:n])
  262. conn.peerModesMutex.Lock()
  263. mode, ok := conn.peerModes[address]
  264. // There's a possible race condition between the two instances of locking
  265. // peerModesMutex: the client might redial in the meantime. Check that the
  266. // mode state is unchanged from when the lock was last held.
  267. if !ok || mode.isObfuscated != true || mode.isIETF != false ||
  268. mode.lastPacketTime != lastPacketTime {
  269. conn.peerModesMutex.Unlock()
  270. return n, addr, false, newTemporaryNetError(
  271. errors.Tracef("unexpected peer mode"))
  272. }
  273. mode.isIETF = isIETF
  274. conn.peerModesMutex.Unlock()
  275. }
  276. }
  277. }
  278. // Do not wrap any err returned by conn.PacketConn.ReadFrom.
  279. return n, addr, isIETF, err
  280. }
  281. type obfuscatorBuffer struct {
  282. buffer [MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE]byte
  283. }
  284. var obfuscatorBufferPool = &sync.Pool{
  285. New: func() interface{} {
  286. return new(obfuscatorBuffer)
  287. },
  288. }
  289. func getMaxPacketSizes(addr net.Addr) (int, int) {
  290. if udpAddr, ok := addr.(*net.UDPAddr); ok && udpAddr.IP.To4() == nil {
  291. return MAX_QUIC_IPV6_PACKET_SIZE, MAX_OBFUSCATED_QUIC_IPV6_PACKET_SIZE
  292. }
  293. return MAX_QUIC_IPV4_PACKET_SIZE, MAX_OBFUSCATED_QUIC_IPV4_PACKET_SIZE
  294. }
  295. func (conn *ObfuscatedPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
  296. n := len(p)
  297. isObfuscated := true
  298. if conn.isServer {
  299. conn.peerModesMutex.Lock()
  300. address := addr.String()
  301. mode, ok := conn.peerModes[address]
  302. isObfuscated = ok && mode.isObfuscated
  303. conn.peerModesMutex.Unlock()
  304. }
  305. if isObfuscated {
  306. maxQUICPacketSize, maxObfuscatedPacketSize := getMaxPacketSizes(addr)
  307. if n > maxQUICPacketSize {
  308. return 0, newTemporaryNetError(errors.Tracef(
  309. "unexpected QUIC packet length: %d", n))
  310. }
  311. // Note: escape analysis showed a local array escaping to the heap,
  312. // so use a buffer pool instead to avoid heap allocation per packet.
  313. b := obfuscatorBufferPool.Get().(*obfuscatorBuffer)
  314. buffer := b.buffer[:]
  315. defer obfuscatorBufferPool.Put(b)
  316. for {
  317. // Note: this zero-memory pattern is compiler optimized:
  318. // https://golang.org/cl/137880043
  319. for i := range buffer {
  320. buffer[i] = 0
  321. }
  322. nonce := buffer[0:NONCE_SIZE]
  323. conn.noncePRNG.Read(nonce)
  324. // Obfuscated QUIC padding results in packets that exceed the
  325. // QUIC max packet size of 1280.
  326. maxPaddingLen := maxObfuscatedPacketSize - (n + (NONCE_SIZE + 1))
  327. if maxPaddingLen < 0 {
  328. maxPaddingLen = 0
  329. }
  330. if maxPaddingLen > MAX_PADDING {
  331. maxPaddingLen = MAX_PADDING
  332. }
  333. paddingLen := conn.paddingPRNG.Intn(maxPaddingLen + 1)
  334. buffer[NONCE_SIZE] = uint8(paddingLen)
  335. padding := buffer[(NONCE_SIZE + 1) : (NONCE_SIZE+1)+paddingLen]
  336. conn.paddingPRNG.Read(padding)
  337. copy(buffer[(NONCE_SIZE+1)+paddingLen:], p)
  338. dataLen := (NONCE_SIZE + 1) + paddingLen + n
  339. cipher, err := chacha20.NewCipher(conn.obfuscationKey[:], nonce)
  340. if err != nil {
  341. return 0, errors.Trace(err)
  342. }
  343. packet := buffer[NONCE_SIZE:dataLen]
  344. cipher.XORKeyStream(packet, packet)
  345. p = buffer[:dataLen]
  346. // Don't use obfuscation that looks like QUIC, or the
  347. // peer will not treat this packet as obfuscated.
  348. isQUIC, _ := isQUICClientHello(p)
  349. if !isQUIC {
  350. break
  351. }
  352. }
  353. }
  354. _, err := conn.PacketConn.WriteTo(p, addr)
  355. // Do not wrap any err returned by conn.PacketConn.WriteTo.
  356. return n, err
  357. }
  358. func isQUICClientHello(buffer []byte) (bool, bool) {
  359. // As this function is called for every packet, it needs to be fast.
  360. //
  361. // As QUIC header parsing is complex, with many cases, we are not
  362. // presently doing that, although this might improve accuracy as we should
  363. // be able to identify the precise offset of indicators based on header
  364. // values.
  365. if isIETFQUICClientHello(buffer) {
  366. return true, true
  367. } else if isgQUICClientHello(buffer) {
  368. return true, false
  369. }
  370. return false, false
  371. }
  372. func isgQUICClientHello(buffer []byte) bool {
  373. // In all currently supported versions, the first client packet contains
  374. // the "CHLO" tag at one of the following offsets. The offset can vary for
  375. // a single version.
  376. //
  377. // Note that v44 does not include the "QUIC version" header field in its
  378. // first client packet.
  379. if (len(buffer) >= 33 &&
  380. buffer[29] == 'C' &&
  381. buffer[30] == 'H' &&
  382. buffer[31] == 'L' &&
  383. buffer[32] == 'O') ||
  384. (len(buffer) >= 35 &&
  385. buffer[31] == 'C' &&
  386. buffer[32] == 'H' &&
  387. buffer[33] == 'L' &&
  388. buffer[34] == 'O') ||
  389. (len(buffer) >= 38 &&
  390. buffer[34] == 'C' &&
  391. buffer[35] == 'H' &&
  392. buffer[36] == 'L' &&
  393. buffer[37] == 'O') {
  394. return true
  395. }
  396. return false
  397. }
  398. func isIETFQUICClientHello(buffer []byte) bool {
  399. // https://tools.ietf.org/html/draft-ietf-quic-transport-23#section-17.2:
  400. //
  401. // Check 1st nibble of byte 0:
  402. // 1... .... = Header Form: Long Header (1)
  403. // .1.. .... = Fixed Bit: True
  404. // ..00 .... = Packet Type: Initial (0)
  405. //
  406. // Then check bytes 1..4 for expected version number.
  407. if len(buffer) < 5 {
  408. return false
  409. }
  410. if buffer[0]>>4 != 0x0c {
  411. return false
  412. }
  413. // IETF QUIC draft-24
  414. return buffer[1] == 0xff &&
  415. buffer[2] == 0 &&
  416. buffer[3] == 0 &&
  417. buffer[4] == 0x18
  418. }