meek.go 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bytes"
  22. "crypto/rand"
  23. "crypto/tls"
  24. "encoding/base64"
  25. "encoding/hex"
  26. "encoding/json"
  27. "errors"
  28. "hash/crc64"
  29. "io"
  30. "net"
  31. "net/http"
  32. "runtime"
  33. "strconv"
  34. "strings"
  35. "sync"
  36. "sync/atomic"
  37. "time"
  38. "github.com/Psiphon-Labs/goarista/monotime"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/box"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  44. tris "github.com/Psiphon-Labs/tls-tris"
  45. )
  46. // MeekServer is based on meek-server.go from Tor and Psiphon:
  47. //
  48. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  49. // CC0 1.0 Universal
  50. //
  51. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
  52. const (
  53. // Protocol version 1 clients can handle arbitrary length response bodies. Older clients
  54. // report no version number and expect at most 64K response bodies.
  55. MEEK_PROTOCOL_VERSION_1 = 1
  56. // Protocol version 2 clients initiate a session by sending an encrypted and obfuscated meek
  57. // cookie with their initial HTTP request. Connection information is contained within the
  58. // encrypted cookie payload. The server inspects the cookie and establishes a new session and
  59. // returns a new random session ID back to client via Set-Cookie header. The client uses this
  60. // session ID on all subsequent requests for the remainder of the session.
  61. MEEK_PROTOCOL_VERSION_2 = 2
  62. // Protocol version 3 clients include resiliency enhancements and will add a Range header
  63. // when retrying a request for a partially downloaded response payload.
  64. MEEK_PROTOCOL_VERSION_3 = 3
  65. MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  66. MEEK_TURN_AROUND_TIMEOUT = 20 * time.Millisecond
  67. MEEK_EXTENDED_TURN_AROUND_TIMEOUT = 100 * time.Millisecond
  68. MEEK_MAX_SESSION_STALENESS = 45 * time.Second
  69. MEEK_HTTP_CLIENT_IO_TIMEOUT = 45 * time.Second
  70. MEEK_MIN_SESSION_ID_LENGTH = 8
  71. MEEK_MAX_SESSION_ID_LENGTH = 20
  72. MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH = 65536
  73. MEEK_DEFAULT_POOL_BUFFER_LENGTH = 65536
  74. MEEK_DEFAULT_POOL_BUFFER_COUNT = 2048
  75. )
  76. // MeekServer implements the meek protocol, which tunnels TCP traffic (in the case of Psiphon,
  77. // Obfuscated SSH traffic) over HTTP. Meek may be fronted (through a CDN) or direct and may be
  78. // HTTP or HTTPS.
  79. //
  80. // Upstream traffic arrives in HTTP request bodies and downstream traffic is sent in response
  81. // bodies. The sequence of traffic for a given flow is associated using a session ID that's
  82. // set as a HTTP cookie for the client to submit with each request.
  83. //
  84. // MeekServer hooks into TunnelServer via the net.Conn interface by transforming the
  85. // HTTP payload traffic for a given session into net.Conn conforming Read()s and Write()s via
  86. // the meekConn struct.
  87. type MeekServer struct {
  88. support *SupportServices
  89. listener net.Listener
  90. tlsConfig *tris.Config
  91. clientHandler func(clientTunnelProtocol string, clientConn net.Conn)
  92. openConns *common.Conns
  93. stopBroadcast <-chan struct{}
  94. sessionsLock sync.RWMutex
  95. sessions map[string]*meekSession
  96. checksumTable *crc64.Table
  97. bufferPool *CachedResponseBufferPool
  98. rateLimitLock sync.Mutex
  99. rateLimitHistory map[string][]monotime.Time
  100. rateLimitCount int
  101. rateLimitSignalGC chan struct{}
  102. }
  103. // NewMeekServer initializes a new meek server.
  104. func NewMeekServer(
  105. support *SupportServices,
  106. listener net.Listener,
  107. useTLS, isFronted, useObfuscatedSessionTickets bool,
  108. clientHandler func(clientTunnelProtocol string, clientConn net.Conn),
  109. stopBroadcast <-chan struct{}) (*MeekServer, error) {
  110. checksumTable := crc64.MakeTable(crc64.ECMA)
  111. bufferLength := MEEK_DEFAULT_POOL_BUFFER_LENGTH
  112. if support.Config.MeekCachedResponsePoolBufferSize != 0 {
  113. bufferLength = support.Config.MeekCachedResponsePoolBufferSize
  114. }
  115. bufferCount := MEEK_DEFAULT_POOL_BUFFER_COUNT
  116. if support.Config.MeekCachedResponsePoolBufferCount != 0 {
  117. bufferCount = support.Config.MeekCachedResponsePoolBufferCount
  118. }
  119. bufferPool := NewCachedResponseBufferPool(bufferLength, bufferCount)
  120. meekServer := &MeekServer{
  121. support: support,
  122. listener: listener,
  123. clientHandler: clientHandler,
  124. openConns: common.NewConns(),
  125. stopBroadcast: stopBroadcast,
  126. sessions: make(map[string]*meekSession),
  127. checksumTable: checksumTable,
  128. bufferPool: bufferPool,
  129. rateLimitHistory: make(map[string][]monotime.Time),
  130. rateLimitSignalGC: make(chan struct{}, 1),
  131. }
  132. if useTLS {
  133. tlsConfig, err := makeMeekTLSConfig(
  134. support, isFronted, useObfuscatedSessionTickets)
  135. if err != nil {
  136. return nil, common.ContextError(err)
  137. }
  138. meekServer.tlsConfig = tlsConfig
  139. }
  140. return meekServer, nil
  141. }
  142. // Run runs the meek server; this function blocks while serving HTTP or
  143. // HTTPS connections on the specified listener. This function also runs
  144. // a goroutine which cleans up expired meek client sessions.
  145. //
  146. // To stop the meek server, both Close() the listener and set the stopBroadcast
  147. // signal specified in NewMeekServer.
  148. func (server *MeekServer) Run() error {
  149. waitGroup := new(sync.WaitGroup)
  150. waitGroup.Add(1)
  151. go func() {
  152. defer waitGroup.Done()
  153. ticker := time.NewTicker(MEEK_MAX_SESSION_STALENESS / 2)
  154. defer ticker.Stop()
  155. for {
  156. select {
  157. case <-ticker.C:
  158. server.deleteExpiredSessions()
  159. case <-server.stopBroadcast:
  160. return
  161. }
  162. }
  163. }()
  164. waitGroup.Add(1)
  165. go func() {
  166. defer waitGroup.Done()
  167. server.rateLimitWorker()
  168. }()
  169. // Serve HTTP or HTTPS
  170. //
  171. // - WriteTimeout may include time awaiting request, as per:
  172. // https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
  173. // - Legacy meek-server wrapped each client HTTP connection with an explicit idle
  174. // timeout net.Conn and didn't use http.Server timeouts. We could do the same
  175. // here (use ActivityMonitoredConn) but the stock http.Server timeouts should
  176. // now be sufficient.
  177. httpServer := &http.Server{
  178. ReadTimeout: MEEK_HTTP_CLIENT_IO_TIMEOUT,
  179. WriteTimeout: MEEK_HTTP_CLIENT_IO_TIMEOUT,
  180. Handler: server,
  181. ConnState: server.httpConnStateCallback,
  182. // Disable auto HTTP/2 (https://golang.org/doc/go1.6)
  183. TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
  184. }
  185. // Note: Serve() will be interrupted by listener.Close() call
  186. var err error
  187. if server.tlsConfig != nil {
  188. httpsServer := HTTPSServer{Server: httpServer}
  189. err = httpsServer.ServeTLS(server.listener, server.tlsConfig)
  190. } else {
  191. err = httpServer.Serve(server.listener)
  192. }
  193. // Can't check for the exact error that Close() will cause in Accept(),
  194. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  195. // explicit stop signal to stop gracefully.
  196. select {
  197. case <-server.stopBroadcast:
  198. err = nil
  199. default:
  200. }
  201. // deleteExpiredSessions calls deleteSession which may block waiting
  202. // for active request handlers to complete; timely shutdown requires
  203. // stopping the listener and closing all existing connections before
  204. // awaiting the reaperWaitGroup.
  205. server.listener.Close()
  206. server.openConns.CloseAll()
  207. waitGroup.Wait()
  208. return err
  209. }
  210. // ServeHTTP handles meek client HTTP requests, where the request body
  211. // contains upstream traffic and the response will contain downstream
  212. // traffic.
  213. func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  214. // Note: no longer requiring that the request method is POST
  215. // Check for the expected meek/session ID cookie.
  216. // Also check for prohibited HTTP headers.
  217. var meekCookie *http.Cookie
  218. for _, c := range request.Cookies() {
  219. meekCookie = c
  220. break
  221. }
  222. if meekCookie == nil || len(meekCookie.Value) == 0 {
  223. log.WithContext().Warning("missing meek cookie")
  224. common.TerminateHTTPConnection(responseWriter, request)
  225. return
  226. }
  227. if len(server.support.Config.MeekProhibitedHeaders) > 0 {
  228. for _, header := range server.support.Config.MeekProhibitedHeaders {
  229. value := request.Header.Get(header)
  230. if header != "" {
  231. log.WithContextFields(LogFields{
  232. "header": header,
  233. "value": value,
  234. }).Warning("prohibited meek header")
  235. common.TerminateHTTPConnection(responseWriter, request)
  236. return
  237. }
  238. }
  239. }
  240. // A valid meek cookie indicates which class of request this is:
  241. //
  242. // 1. A new meek session. Create a new session ID and proceed with
  243. // relaying tunnel traffic.
  244. //
  245. // 2. An existing meek session. Resume relaying tunnel traffic.
  246. //
  247. // 3. A request to an endpoint. This meek connection is not for relaying
  248. // tunnel traffic. Instead, the request is handed off to a custom handler.
  249. sessionID, session, endPoint, clientIP, err := server.getSessionOrEndpoint(request, meekCookie)
  250. if err != nil {
  251. // Debug since session cookie errors commonly occur during
  252. // normal operation.
  253. log.WithContextFields(LogFields{"error": err}).Debug("session lookup failed")
  254. common.TerminateHTTPConnection(responseWriter, request)
  255. return
  256. }
  257. if endPoint != "" {
  258. // Endpoint mode. Currently, this means it's handled by the tactics
  259. // request handler.
  260. geoIPData := server.support.GeoIPService.Lookup(clientIP)
  261. handled := server.support.TacticsServer.HandleEndPoint(
  262. endPoint, common.GeoIPData(geoIPData), responseWriter, request)
  263. if !handled {
  264. log.WithContextFields(LogFields{"endPoint": endPoint}).Info("unhandled endpoint")
  265. common.TerminateHTTPConnection(responseWriter, request)
  266. }
  267. return
  268. }
  269. // Tunnel relay mode.
  270. // Ensure that there's only one concurrent request handler per client
  271. // session. Depending on the nature of a network disruption, it can
  272. // happen that a client detects a failure and retries while the server
  273. // is still streaming response in the handler for the _previous_ client
  274. // request.
  275. //
  276. // Even if the session.cachedResponse were safe for concurrent
  277. // use (it is not), concurrent handling could lead to loss of session
  278. // since upstream data read by the first request may not reach the
  279. // cached response before the second request reads the cached data.
  280. //
  281. // The existing handler will stream response data, holding the lock,
  282. // for no more than MEEK_EXTENDED_TURN_AROUND_TIMEOUT.
  283. //
  284. // TODO: interrupt an existing handler? The existing handler will be
  285. // sending data to the cached response, but if that buffer fills, the
  286. // session will be lost.
  287. requestNumber := atomic.AddInt64(&session.requestCount, 1)
  288. // Wait for the existing request to complete.
  289. session.lock.Lock()
  290. defer session.lock.Unlock()
  291. // If a newer request has arrived while waiting, discard this one.
  292. // Do not delay processing the newest request.
  293. //
  294. // If the session expired and was deleted while this request was waiting,
  295. // discard this request. The session is no longer valid, and the final call
  296. // to session.cachedResponse.Reset may have already occured, so any further
  297. // session.cachedResponse access may deplete resources (fail to refill the pool).
  298. if atomic.LoadInt64(&session.requestCount) > requestNumber || session.deleted {
  299. common.TerminateHTTPConnection(responseWriter, request)
  300. return
  301. }
  302. // pumpReads causes a TunnelServer/SSH goroutine blocking on a Read to
  303. // read the request body as upstream traffic.
  304. // TODO: run pumpReads and pumpWrites concurrently?
  305. // pumpReads checksums the request payload and skips relaying it when
  306. // it matches the immediately previous request payload. This allows
  307. // clients to resend request payloads, when retrying due to connection
  308. // interruption, without knowing whether the server has received or
  309. // relayed the data.
  310. err = session.clientConn.pumpReads(request.Body)
  311. if err != nil {
  312. if err != io.EOF {
  313. // Debug since errors such as "i/o timeout" occur during normal operation;
  314. // also, golang network error messages may contain client IP.
  315. log.WithContextFields(LogFields{"error": err}).Debug("read request failed")
  316. }
  317. common.TerminateHTTPConnection(responseWriter, request)
  318. // Note: keep session open to allow client to retry
  319. return
  320. }
  321. // Set cookie before writing the response.
  322. if session.meekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 && session.sessionIDSent == false {
  323. // Replace the meek cookie with the session ID.
  324. // SetCookie for the the session ID cookie is only set once, to reduce overhead. This
  325. // session ID value replaces the original meek cookie value.
  326. http.SetCookie(responseWriter, &http.Cookie{Name: meekCookie.Name, Value: sessionID})
  327. session.sessionIDSent = true
  328. }
  329. // When streaming data into the response body, a copy is
  330. // retained in the cachedResponse buffer. This allows the
  331. // client to retry and request that the response be resent
  332. // when the HTTP connection is interrupted.
  333. //
  334. // If a Range header is present, the client is retrying,
  335. // possibly after having received a partial response. In
  336. // this case, use any cached response to attempt to resend
  337. // the response, starting from the resend position the client
  338. // indicates.
  339. //
  340. // When the resend position is not available -- because the
  341. // cachedResponse buffer could not hold it -- the client session
  342. // is closed, as there's no way to resume streaming the payload
  343. // uninterrupted.
  344. //
  345. // The client may retry before a cached response is prepared,
  346. // so a cached response is not always used when a Range header
  347. // is present.
  348. //
  349. // TODO: invalid Range header is ignored; should it be otherwise?
  350. position, isRetry := checkRangeHeader(request)
  351. if isRetry {
  352. atomic.AddInt64(&session.metricClientRetries, 1)
  353. }
  354. hasCompleteCachedResponse := session.cachedResponse.HasPosition(0)
  355. // The client is not expected to send position > 0 when there is
  356. // no cached response; let that case fall through to the next
  357. // HasPosition check which will fail and close the session.
  358. var responseSize int
  359. var responseError error
  360. if isRetry && (hasCompleteCachedResponse || position > 0) {
  361. if !session.cachedResponse.HasPosition(position) {
  362. greaterThanSwapInt64(&session.metricCachedResponseMissPosition, int64(position))
  363. common.TerminateHTTPConnection(responseWriter, request)
  364. session.delete(true)
  365. return
  366. }
  367. responseWriter.WriteHeader(http.StatusPartialContent)
  368. // TODO:
  369. // - enforce a max extended buffer count per client, for
  370. // fairness? Throttling may make this unnecessary.
  371. // - cachedResponse can now start releasing extended buffers,
  372. // as response bytes before "position" will never be requested
  373. // again?
  374. responseSize, responseError = session.cachedResponse.CopyFromPosition(position, responseWriter)
  375. greaterThanSwapInt64(&session.metricPeakCachedResponseHitSize, int64(responseSize))
  376. // The client may again fail to receive the payload and may again
  377. // retry, so not yet releasing cachedResponse buffers.
  378. } else {
  379. // _Now_ we release buffers holding data from the previous
  380. // response. And then immediately stream the new response into
  381. // newly acquired buffers.
  382. session.cachedResponse.Reset()
  383. // Note: this code depends on an implementation detail of
  384. // io.MultiWriter: a Write() to the MultiWriter writes first
  385. // to the cache, and then to the response writer. So if the
  386. // write to the response writer fails, the payload is cached.
  387. multiWriter := io.MultiWriter(session.cachedResponse, responseWriter)
  388. // The client expects 206, not 200, whenever it sets a Range header,
  389. // which it may do even when no cached response is prepared.
  390. if isRetry {
  391. responseWriter.WriteHeader(http.StatusPartialContent)
  392. }
  393. // pumpWrites causes a TunnelServer/SSH goroutine blocking on a Write to
  394. // write its downstream traffic through to the response body.
  395. responseSize, responseError = session.clientConn.pumpWrites(multiWriter)
  396. greaterThanSwapInt64(&session.metricPeakResponseSize, int64(responseSize))
  397. greaterThanSwapInt64(&session.metricPeakCachedResponseSize, int64(session.cachedResponse.Available()))
  398. }
  399. // responseError is the result of writing the body either from CopyFromPosition or pumpWrites
  400. if responseError != nil {
  401. if responseError != io.EOF {
  402. // Debug since errors such as "i/o timeout" occur during normal operation;
  403. // also, golang network error messages may contain client IP.
  404. log.WithContextFields(LogFields{"error": responseError}).Debug("write response failed")
  405. }
  406. common.TerminateHTTPConnection(responseWriter, request)
  407. // Note: keep session open to allow client to retry
  408. return
  409. }
  410. }
  411. func checkRangeHeader(request *http.Request) (int, bool) {
  412. rangeHeader := request.Header.Get("Range")
  413. if rangeHeader == "" {
  414. return 0, false
  415. }
  416. prefix := "bytes="
  417. suffix := "-"
  418. if !strings.HasPrefix(rangeHeader, prefix) ||
  419. !strings.HasSuffix(rangeHeader, suffix) {
  420. return 0, false
  421. }
  422. rangeHeader = strings.TrimPrefix(rangeHeader, prefix)
  423. rangeHeader = strings.TrimSuffix(rangeHeader, suffix)
  424. position, err := strconv.Atoi(rangeHeader)
  425. if err != nil {
  426. return 0, false
  427. }
  428. return position, true
  429. }
  430. // getSessionOrEndpoint checks if the cookie corresponds to an existing tunnel
  431. // relay session ID. If no session is found, the cookie must be an obfuscated
  432. // meek cookie. A new session is created when the meek cookie indicates relay
  433. // mode; or the endpoint is returned when the meek cookie indicates endpoint
  434. // mode.
  435. func (server *MeekServer) getSessionOrEndpoint(
  436. request *http.Request, meekCookie *http.Cookie) (string, *meekSession, string, string, error) {
  437. // Check for an existing session.
  438. server.sessionsLock.RLock()
  439. existingSessionID := meekCookie.Value
  440. session, ok := server.sessions[existingSessionID]
  441. server.sessionsLock.RUnlock()
  442. if ok {
  443. // TODO: can multiple http client connections using same session cookie
  444. // cause race conditions on session struct?
  445. session.touch()
  446. return existingSessionID, session, "", "", nil
  447. }
  448. // Determine the client remote address, which is used for geolocation
  449. // and stats. When an intermediate proxy or CDN is in use, we may be
  450. // able to determine the original client address by inspecting HTTP
  451. // headers such as X-Forwarded-For.
  452. clientIP := strings.Split(request.RemoteAddr, ":")[0]
  453. if len(server.support.Config.MeekProxyForwardedForHeaders) > 0 {
  454. for _, header := range server.support.Config.MeekProxyForwardedForHeaders {
  455. value := request.Header.Get(header)
  456. if len(value) > 0 {
  457. // Some headers, such as X-Forwarded-For, are a comma-separated
  458. // list of IPs (each proxy in a chain). The first IP should be
  459. // the client IP.
  460. proxyClientIP := strings.Split(value, ",")[0]
  461. if net.ParseIP(proxyClientIP) != nil &&
  462. server.support.GeoIPService.Lookup(proxyClientIP).Country != GEOIP_UNKNOWN_VALUE {
  463. clientIP = proxyClientIP
  464. break
  465. }
  466. }
  467. }
  468. }
  469. if server.rateLimit(clientIP) {
  470. return "", nil, "", "", common.ContextError(errors.New("rate limit exceeded"))
  471. }
  472. // The session is new (or expired). Treat the cookie value as a new meek
  473. // cookie, extract the payload, and create a new session.
  474. payloadJSON, err := getMeekCookiePayload(server.support, meekCookie.Value)
  475. if err != nil {
  476. return "", nil, "", "", common.ContextError(err)
  477. }
  478. // Note: this meek server ignores legacy values PsiphonClientSessionId
  479. // and PsiphonServerAddress.
  480. var clientSessionData protocol.MeekCookieData
  481. err = json.Unmarshal(payloadJSON, &clientSessionData)
  482. if err != nil {
  483. return "", nil, "", "", common.ContextError(err)
  484. }
  485. // Handle endpoints before enforcing the GetEstablishTunnels check.
  486. // Currently, endpoints are tactics requests, and we allow these to be
  487. // handled by servers which would otherwise reject new tunnels.
  488. if clientSessionData.EndPoint != "" {
  489. return "", nil, clientSessionData.EndPoint, clientIP, nil
  490. }
  491. // Don't create new sessions when not establishing. A subsequent SSH handshake
  492. // will not succeed, so creating a meek session just wastes resources.
  493. if server.support.TunnelServer != nil &&
  494. !server.support.TunnelServer.GetEstablishTunnels() {
  495. return "", nil, "", "", common.ContextError(errors.New("not establishing tunnels"))
  496. }
  497. // Create a new session
  498. bufferLength := MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH
  499. if server.support.Config.MeekCachedResponseBufferSize != 0 {
  500. bufferLength = server.support.Config.MeekCachedResponseBufferSize
  501. }
  502. cachedResponse := NewCachedResponse(bufferLength, server.bufferPool)
  503. session = &meekSession{
  504. meekProtocolVersion: clientSessionData.MeekProtocolVersion,
  505. sessionIDSent: false,
  506. cachedResponse: cachedResponse,
  507. }
  508. session.touch()
  509. // Create a new meek conn that will relay the payload
  510. // between meek request/responses and the tunnel server client
  511. // handler. The client IP is also used to initialize the
  512. // meek conn with a useful value to return when the tunnel
  513. // server calls conn.RemoteAddr() to get the client's IP address.
  514. // Assumes clientIP is a valid IP address; the port value is a stub
  515. // and is expected to be ignored.
  516. clientConn := newMeekConn(
  517. server,
  518. session,
  519. &net.TCPAddr{
  520. IP: net.ParseIP(clientIP),
  521. Port: 0,
  522. },
  523. clientSessionData.MeekProtocolVersion)
  524. session.clientConn = clientConn
  525. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  526. // meek cookie to a session ID; v1 clients always send the
  527. // original meek cookie value with each request. The issue with
  528. // v1 is that clients which wake after a device sleep will attempt
  529. // to resume a meek session and the server can't differentiate
  530. // between resuming a session and creating a new session. This
  531. // causes the v1 client connection to hang/timeout.
  532. sessionID := meekCookie.Value
  533. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  534. sessionID, err = makeMeekSessionID()
  535. if err != nil {
  536. return "", nil, "", "", common.ContextError(err)
  537. }
  538. }
  539. server.sessionsLock.Lock()
  540. server.sessions[sessionID] = session
  541. server.sessionsLock.Unlock()
  542. // Note: from the tunnel server's perspective, this client connection
  543. // will close when session.delete calls Close() on the meekConn.
  544. server.clientHandler(clientSessionData.ClientTunnelProtocol, session.clientConn)
  545. return sessionID, session, "", "", nil
  546. }
  547. func (server *MeekServer) rateLimit(clientIP string) bool {
  548. historySize, thresholdSeconds, regions, ISPs, GCTriggerCount, _ :=
  549. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  550. if historySize == 0 {
  551. return false
  552. }
  553. if len(regions) > 0 || len(ISPs) > 0 {
  554. // TODO: avoid redundant GeoIP lookups?
  555. geoIPData := server.support.GeoIPService.Lookup(clientIP)
  556. if len(regions) > 0 {
  557. if !common.Contains(regions, geoIPData.Country) {
  558. return false
  559. }
  560. }
  561. if len(ISPs) > 0 {
  562. if !common.Contains(ISPs, geoIPData.ISP) {
  563. return false
  564. }
  565. }
  566. }
  567. limit := true
  568. triggerGC := false
  569. now := monotime.Now()
  570. threshold := now.Add(-time.Duration(thresholdSeconds) * time.Second)
  571. server.rateLimitLock.Lock()
  572. history, ok := server.rateLimitHistory[clientIP]
  573. if !ok || len(history) != historySize {
  574. history = make([]monotime.Time, historySize)
  575. server.rateLimitHistory[clientIP] = history
  576. }
  577. for i := 0; i < len(history); i++ {
  578. if history[i] == 0 || history[i].Before(threshold) {
  579. limit = false
  580. }
  581. if i == len(history)-1 {
  582. history[i] = now
  583. } else {
  584. history[i] = history[i+1]
  585. }
  586. }
  587. if limit {
  588. server.rateLimitCount += 1
  589. if server.rateLimitCount >= GCTriggerCount {
  590. triggerGC = true
  591. server.rateLimitCount = 0
  592. }
  593. }
  594. server.rateLimitLock.Unlock()
  595. if triggerGC {
  596. select {
  597. case server.rateLimitSignalGC <- *new(struct{}):
  598. default:
  599. }
  600. }
  601. return limit
  602. }
  603. func (server *MeekServer) rateLimitWorker() {
  604. _, _, _, _, _, reapFrequencySeconds :=
  605. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  606. timer := time.NewTimer(time.Duration(reapFrequencySeconds) * time.Second)
  607. defer timer.Stop()
  608. for {
  609. select {
  610. case <-timer.C:
  611. _, thresholdSeconds, _, _, _, reapFrequencySeconds :=
  612. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  613. server.rateLimitLock.Lock()
  614. threshold := monotime.Now().Add(-time.Duration(thresholdSeconds) * time.Second)
  615. for key, history := range server.rateLimitHistory {
  616. reap := true
  617. for i := 0; i < len(history); i++ {
  618. if history[i] != 0 && !history[i].Before(threshold) {
  619. reap = false
  620. }
  621. }
  622. if reap {
  623. delete(server.rateLimitHistory, key)
  624. }
  625. }
  626. // Enable rate limit history map to be garbage collected when possible.
  627. if len(server.rateLimitHistory) == 0 {
  628. server.rateLimitHistory = make(map[string][]monotime.Time)
  629. }
  630. server.rateLimitLock.Unlock()
  631. timer.Reset(time.Duration(reapFrequencySeconds) * time.Second)
  632. case <-server.rateLimitSignalGC:
  633. runtime.GC()
  634. case <-server.stopBroadcast:
  635. return
  636. }
  637. }
  638. }
  639. func (server *MeekServer) deleteSession(sessionID string) {
  640. // Don't obtain the server.sessionsLock write lock until modifying
  641. // server.sessions, as the session.delete can block for up to
  642. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  643. // concurrently.
  644. //
  645. // Since a lock isn't held for the duration, concurrent calls to
  646. // deleteSession with the same sessionID could happen; this is
  647. // not expected since only the reaper goroutine calls deleteExpiredSessions
  648. // (and in any case concurrent execution of the ok block is not an issue).
  649. server.sessionsLock.RLock()
  650. session, ok := server.sessions[sessionID]
  651. server.sessionsLock.RUnlock()
  652. if ok {
  653. session.delete(false)
  654. server.sessionsLock.Lock()
  655. delete(server.sessions, sessionID)
  656. server.sessionsLock.Unlock()
  657. }
  658. }
  659. func (server *MeekServer) deleteExpiredSessions() {
  660. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  661. // so grab a snapshot list of expired sessions and do not hold a lock for
  662. // the duration of deleteExpiredSessions. This allows new sessions to be
  663. // added concurrently.
  664. //
  665. // New sessions added after the snapshot is taken will be checked for
  666. // expiry on subsequent periodic calls to deleteExpiredSessions.
  667. //
  668. // To avoid long delays in releasing resources, individual deletes are
  669. // performed concurrently.
  670. server.sessionsLock.Lock()
  671. expiredSessionIDs := make([]string, 0)
  672. for sessionID, session := range server.sessions {
  673. if session.expired() {
  674. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  675. }
  676. }
  677. server.sessionsLock.Unlock()
  678. start := monotime.Now()
  679. deleteWaitGroup := new(sync.WaitGroup)
  680. for _, sessionID := range expiredSessionIDs {
  681. deleteWaitGroup.Add(1)
  682. go func(sessionID string) {
  683. defer deleteWaitGroup.Done()
  684. server.deleteSession(sessionID)
  685. }(sessionID)
  686. }
  687. deleteWaitGroup.Wait()
  688. log.WithContextFields(
  689. LogFields{"elapsed time": monotime.Since(start)}).Debug("deleted expired sessions")
  690. }
  691. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  692. // meek server.
  693. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  694. switch connState {
  695. case http.StateNew:
  696. server.openConns.Add(conn)
  697. case http.StateHijacked, http.StateClosed:
  698. server.openConns.Remove(conn)
  699. }
  700. }
  701. type meekSession struct {
  702. // Note: 64-bit ints used with atomic operations are placed
  703. // at the start of struct to ensure 64-bit alignment.
  704. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  705. lastActivity int64
  706. requestCount int64
  707. metricClientRetries int64
  708. metricPeakResponseSize int64
  709. metricPeakCachedResponseSize int64
  710. metricPeakCachedResponseHitSize int64
  711. metricCachedResponseMissPosition int64
  712. lock sync.Mutex
  713. deleted bool
  714. clientConn *meekConn
  715. meekProtocolVersion int
  716. sessionIDSent bool
  717. cachedResponse *CachedResponse
  718. }
  719. func (session *meekSession) touch() {
  720. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  721. }
  722. func (session *meekSession) expired() bool {
  723. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  724. return monotime.Since(lastActivity) > MEEK_MAX_SESSION_STALENESS
  725. }
  726. // delete releases all resources allocated by a session.
  727. func (session *meekSession) delete(haveLock bool) {
  728. // TODO: close the persistent HTTP client connection, if one exists?
  729. // This final call session.cachedResponse.Reset releases shared resources.
  730. //
  731. // This call requires exclusive access. session.lock is be obtained before
  732. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  733. // request for this session is being processed concurrently, and pending
  734. // requests will block at session.lock.
  735. //
  736. // This logic assumes that no further session.cachedResponse access occurs,
  737. // or else resources may deplete (buffers won't be returned to the pool).
  738. // These requirements are achieved by obtaining the lock, setting
  739. // session.deleted, and any subsequent request handlers checking
  740. // session.deleted immediately after obtaining the lock.
  741. //
  742. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  743. // the timeout for any active request handler processing a session
  744. // request.
  745. //
  746. // When the lock must be acquired, clientConn.Close is called first, to
  747. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  748. session.clientConn.Close()
  749. if !haveLock {
  750. session.lock.Lock()
  751. }
  752. // Release all extended buffers back to the pool.
  753. // session.cachedResponse.Reset is not safe for concurrent calls.
  754. session.cachedResponse.Reset()
  755. session.deleted = true
  756. if !haveLock {
  757. session.lock.Unlock()
  758. }
  759. }
  760. // GetMetrics implements the common.MetricsSource interface.
  761. func (session *meekSession) GetMetrics() common.LogFields {
  762. logFields := make(common.LogFields)
  763. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  764. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  765. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  766. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  767. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  768. return logFields
  769. }
  770. // makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
  771. // Currently, this config is optimized for fronted meek where the nature
  772. // of the connection is non-circumvention; it's optimized for performance
  773. // assuming the peer is an uncensored CDN.
  774. func makeMeekTLSConfig(
  775. support *SupportServices,
  776. isFronted, useObfuscatedSessionTickets bool) (*tris.Config, error) {
  777. certificate, privateKey, err := common.GenerateWebServerCertificate(common.GenerateHostName())
  778. if err != nil {
  779. return nil, common.ContextError(err)
  780. }
  781. tlsCertificate, err := tris.X509KeyPair(
  782. []byte(certificate), []byte(privateKey))
  783. if err != nil {
  784. return nil, common.ContextError(err)
  785. }
  786. config := &tris.Config{
  787. Certificates: []tris.Certificate{tlsCertificate},
  788. NextProtos: []string{"http/1.1"},
  789. MinVersion: tris.VersionTLS10,
  790. UseExtendedMasterSecret: true,
  791. }
  792. if isFronted {
  793. // This is a reordering of the supported CipherSuites in golang 1.6. Non-ephemeral key
  794. // CipherSuites greatly reduce server load, and we try to select these since the meek
  795. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  796. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  797. // by ephemeral key CipherSuites.
  798. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  799. //
  800. // This optimization is applied only when there's a CDN in front of the meek server; in
  801. // unfronted cases we prefer a more natural TLS handshake.
  802. config.CipherSuites = []uint16{
  803. tris.TLS_RSA_WITH_AES_128_GCM_SHA256,
  804. tris.TLS_RSA_WITH_AES_256_GCM_SHA384,
  805. tris.TLS_RSA_WITH_RC4_128_SHA,
  806. tris.TLS_RSA_WITH_AES_128_CBC_SHA,
  807. tris.TLS_RSA_WITH_AES_256_CBC_SHA,
  808. tris.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  809. tris.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  810. tris.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  811. tris.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  812. tris.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  813. tris.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  814. tris.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  815. tris.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  816. tris.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  817. tris.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  818. tris.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  819. tris.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  820. }
  821. config.PreferServerCipherSuites = true
  822. }
  823. if useObfuscatedSessionTickets {
  824. // See obfuscated session ticket overview
  825. // in NewObfuscatedClientSessionCache.
  826. var obfuscatedSessionTicketKey [32]byte
  827. key, err := hex.DecodeString(support.Config.MeekObfuscatedKey)
  828. if err == nil && len(key) != 32 {
  829. err = errors.New("invalid obfuscated session key length")
  830. }
  831. if err != nil {
  832. return nil, common.ContextError(err)
  833. }
  834. copy(obfuscatedSessionTicketKey[:], key)
  835. var standardSessionTicketKey [32]byte
  836. _, err = rand.Read(standardSessionTicketKey[:])
  837. if err != nil {
  838. return nil, common.ContextError(err)
  839. }
  840. // Note: SessionTicketKey needs to be set, or else, it appears,
  841. // tris.Config.serverInit() will clobber the value set by
  842. // SetSessionTicketKeys.
  843. config.SessionTicketKey = obfuscatedSessionTicketKey
  844. config.SetSessionTicketKeys([][32]byte{
  845. standardSessionTicketKey,
  846. obfuscatedSessionTicketKey})
  847. }
  848. return config, nil
  849. }
  850. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  851. // payload is base64 encoded, obfuscated, and NaCl encrypted.
  852. func getMeekCookiePayload(support *SupportServices, cookieValue string) ([]byte, error) {
  853. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  854. if err != nil {
  855. return nil, common.ContextError(err)
  856. }
  857. // The data consists of an obfuscated seed message prepended
  858. // to the obfuscated, encrypted payload. The server obfuscator
  859. // will read the seed message, leaving the remaining encrypted
  860. // data in the reader.
  861. reader := bytes.NewReader(decodedValue[:])
  862. obfuscator, err := obfuscator.NewServerObfuscator(
  863. reader,
  864. &obfuscator.ObfuscatorConfig{Keyword: support.Config.MeekObfuscatedKey})
  865. if err != nil {
  866. return nil, common.ContextError(err)
  867. }
  868. offset, err := reader.Seek(0, 1)
  869. if err != nil {
  870. return nil, common.ContextError(err)
  871. }
  872. encryptedPayload := decodedValue[offset:]
  873. obfuscator.ObfuscateClientToServer(encryptedPayload)
  874. var nonce [24]byte
  875. var privateKey, ephemeralPublicKey [32]byte
  876. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  877. support.Config.MeekCookieEncryptionPrivateKey)
  878. if err != nil {
  879. return nil, common.ContextError(err)
  880. }
  881. copy(privateKey[:], decodedPrivateKey)
  882. if len(encryptedPayload) < 32 {
  883. return nil, common.ContextError(errors.New("unexpected encrypted payload size"))
  884. }
  885. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  886. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  887. if !ok {
  888. return nil, common.ContextError(errors.New("open box failed"))
  889. }
  890. return payload, nil
  891. }
  892. // makeMeekSessionID creates a new session ID. The variable size is intended to
  893. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  894. func makeMeekSessionID() (string, error) {
  895. size := MEEK_MIN_SESSION_ID_LENGTH +
  896. prng.Intn(MEEK_MAX_SESSION_ID_LENGTH-MEEK_MIN_SESSION_ID_LENGTH)
  897. sessionID, err := common.MakeSecureRandomBytes(size)
  898. if err != nil {
  899. return "", common.ContextError(err)
  900. }
  901. return base64.RawURLEncoding.EncodeToString(sessionID), nil
  902. }
  903. // meekConn implements the net.Conn interface and is to be used as a client
  904. // connection by the tunnel server (being passed to sshServer.handleClient).
  905. // meekConn bridges net/http request/response payload readers and writers
  906. // and goroutines calling Read()s and Write()s.
  907. type meekConn struct {
  908. meekServer *MeekServer
  909. meekSession *meekSession
  910. remoteAddr net.Addr
  911. protocolVersion int
  912. closeBroadcast chan struct{}
  913. closed int32
  914. lastReadChecksum *uint64
  915. readLock sync.Mutex
  916. emptyReadBuffer chan *bytes.Buffer
  917. partialReadBuffer chan *bytes.Buffer
  918. fullReadBuffer chan *bytes.Buffer
  919. writeLock sync.Mutex
  920. nextWriteBuffer chan []byte
  921. writeResult chan error
  922. }
  923. func newMeekConn(
  924. meekServer *MeekServer,
  925. meekSession *meekSession,
  926. remoteAddr net.Addr,
  927. protocolVersion int) *meekConn {
  928. conn := &meekConn{
  929. meekServer: meekServer,
  930. meekSession: meekSession,
  931. remoteAddr: remoteAddr,
  932. protocolVersion: protocolVersion,
  933. closeBroadcast: make(chan struct{}),
  934. closed: 0,
  935. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  936. partialReadBuffer: make(chan *bytes.Buffer, 1),
  937. fullReadBuffer: make(chan *bytes.Buffer, 1),
  938. nextWriteBuffer: make(chan []byte, 1),
  939. writeResult: make(chan error, 1),
  940. }
  941. // Read() calls and pumpReads() are synchronized by exchanging control
  942. // of a single readBuffer. This is the same scheme used in and described
  943. // in psiphon.MeekConn.
  944. conn.emptyReadBuffer <- new(bytes.Buffer)
  945. return conn
  946. }
  947. // pumpReads causes goroutines blocking on meekConn.Read() to read
  948. // from the specified reader. This function blocks until the reader
  949. // is fully consumed or the meekConn is closed. A read buffer allows
  950. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  951. // without a Read() immediately consuming the bytes, but there's still
  952. // a possibility of a stall if no Read() calls are made after this
  953. // read buffer is full.
  954. // Note: assumes only one concurrent call to pumpReads
  955. func (conn *meekConn) pumpReads(reader io.Reader) error {
  956. // Use either an empty or partial buffer. By using a partial
  957. // buffer, pumpReads will not block if the Read() caller has
  958. // not fully drained the read buffer.
  959. var readBuffer *bytes.Buffer
  960. select {
  961. case readBuffer = <-conn.emptyReadBuffer:
  962. case readBuffer = <-conn.partialReadBuffer:
  963. case <-conn.closeBroadcast:
  964. return io.EOF
  965. }
  966. newDataOffset := readBuffer.Len()
  967. // Since we need to read the full request payload in order to
  968. // take its checksum before relaying it, the read buffer can
  969. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  970. // +1 allows for an explicit check for request payloads that
  971. // exceed the maximum permitted length.
  972. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  973. n, err := readBuffer.ReadFrom(limitReader)
  974. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  975. err = errors.New("invalid request payload length")
  976. }
  977. // If the request read fails, don't relay the new data. This allows
  978. // the client to retry and resend its request payload without
  979. // interrupting/duplicating the payload flow.
  980. if err != nil {
  981. readBuffer.Truncate(newDataOffset)
  982. conn.replaceReadBuffer(readBuffer)
  983. return common.ContextError(err)
  984. }
  985. // Check if request payload checksum matches immediately
  986. // previous payload. On match, assume this is a client retry
  987. // sending payload that was already relayed and skip this
  988. // payload. Payload is OSSH ciphertext and almost surely
  989. // will not repeat. In the highly unlikely case that it does,
  990. // the underlying SSH connection will fail and the client
  991. // must reconnect.
  992. checksum := crc64.Checksum(
  993. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  994. if conn.lastReadChecksum == nil {
  995. conn.lastReadChecksum = new(uint64)
  996. } else if *conn.lastReadChecksum == checksum {
  997. readBuffer.Truncate(newDataOffset)
  998. }
  999. *conn.lastReadChecksum = checksum
  1000. conn.replaceReadBuffer(readBuffer)
  1001. return nil
  1002. }
  1003. var errMeekConnectionHasClosed = errors.New("meek connection has closed")
  1004. // Read reads from the meekConn into buffer. Read blocks until
  1005. // some data is read or the meekConn closes. Under the hood, it
  1006. // waits for pumpReads to submit a reader to read from.
  1007. // Note: lock is to conform with net.Conn concurrency semantics
  1008. func (conn *meekConn) Read(buffer []byte) (int, error) {
  1009. conn.readLock.Lock()
  1010. defer conn.readLock.Unlock()
  1011. var readBuffer *bytes.Buffer
  1012. select {
  1013. case readBuffer = <-conn.partialReadBuffer:
  1014. case readBuffer = <-conn.fullReadBuffer:
  1015. case <-conn.closeBroadcast:
  1016. return 0, common.ContextError(errMeekConnectionHasClosed)
  1017. }
  1018. n, err := readBuffer.Read(buffer)
  1019. conn.replaceReadBuffer(readBuffer)
  1020. return n, err
  1021. }
  1022. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  1023. length := readBuffer.Len()
  1024. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1025. conn.fullReadBuffer <- readBuffer
  1026. } else if length == 0 {
  1027. conn.emptyReadBuffer <- readBuffer
  1028. } else {
  1029. conn.partialReadBuffer <- readBuffer
  1030. }
  1031. }
  1032. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  1033. // to the specified writer. This function blocks until the meek response
  1034. // body limits (size for protocol v1, turn around time for protocol v2+)
  1035. // are met, or the meekConn is closed.
  1036. // Note: channel scheme assumes only one concurrent call to pumpWrites
  1037. func (conn *meekConn) pumpWrites(writer io.Writer) (int, error) {
  1038. startTime := monotime.Now()
  1039. timeout := time.NewTimer(MEEK_TURN_AROUND_TIMEOUT)
  1040. defer timeout.Stop()
  1041. n := 0
  1042. for {
  1043. select {
  1044. case buffer := <-conn.nextWriteBuffer:
  1045. written, err := writer.Write(buffer)
  1046. n += written
  1047. // Assumes that writeResult won't block.
  1048. // Note: always send the err to writeResult,
  1049. // as the Write() caller is blocking on this.
  1050. conn.writeResult <- err
  1051. if err != nil {
  1052. return n, err
  1053. }
  1054. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  1055. // Pre-protocol version 1 clients expect at most
  1056. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  1057. return n, nil
  1058. }
  1059. totalElapsedTime := monotime.Since(startTime) / time.Millisecond
  1060. if totalElapsedTime >= MEEK_EXTENDED_TURN_AROUND_TIMEOUT {
  1061. return n, nil
  1062. }
  1063. timeout.Reset(MEEK_TURN_AROUND_TIMEOUT)
  1064. case <-timeout.C:
  1065. return n, nil
  1066. case <-conn.closeBroadcast:
  1067. return n, common.ContextError(errMeekConnectionHasClosed)
  1068. }
  1069. }
  1070. }
  1071. // Write writes the buffer to the meekConn. It blocks until the
  1072. // entire buffer is written to or the meekConn closes. Under the
  1073. // hood, it waits for sufficient pumpWrites calls to consume the
  1074. // write buffer.
  1075. // Note: lock is to conform with net.Conn concurrency semantics
  1076. func (conn *meekConn) Write(buffer []byte) (int, error) {
  1077. conn.writeLock.Lock()
  1078. defer conn.writeLock.Unlock()
  1079. // TODO: may be more efficient to send whole buffer
  1080. // and have pumpWrites stash partial buffer when can't
  1081. // send it all.
  1082. n := 0
  1083. for n < len(buffer) {
  1084. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1085. if end > len(buffer) {
  1086. end = len(buffer)
  1087. }
  1088. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  1089. // to ensure compatibility with v1 protocol.
  1090. chunk := buffer[n:end]
  1091. select {
  1092. case conn.nextWriteBuffer <- chunk:
  1093. case <-conn.closeBroadcast:
  1094. return n, common.ContextError(errMeekConnectionHasClosed)
  1095. }
  1096. // Wait for the buffer to be processed.
  1097. select {
  1098. case _ = <-conn.writeResult:
  1099. // The err from conn.writeResult comes from the
  1100. // io.MultiWriter used in pumpWrites, which writes
  1101. // to both the cached response and the HTTP response.
  1102. //
  1103. // Don't stop on error here, since only writing
  1104. // to the HTTP response will fail, and the client
  1105. // may retry and use the cached response.
  1106. //
  1107. // It's possible that the cached response buffer
  1108. // is too small for the client to successfully
  1109. // retry, but that cannot be determined. In this
  1110. // case, the meek connection will eventually fail.
  1111. //
  1112. // err is already logged in ServeHTTP.
  1113. case <-conn.closeBroadcast:
  1114. return n, common.ContextError(errMeekConnectionHasClosed)
  1115. }
  1116. n += len(chunk)
  1117. }
  1118. return n, nil
  1119. }
  1120. // Close closes the meekConn. This will interrupt any blocked
  1121. // Read, Write, pumpReads, and pumpWrites.
  1122. func (conn *meekConn) Close() error {
  1123. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  1124. close(conn.closeBroadcast)
  1125. }
  1126. return nil
  1127. }
  1128. // Stub implementation of net.Conn.LocalAddr
  1129. func (conn *meekConn) LocalAddr() net.Addr {
  1130. return nil
  1131. }
  1132. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  1133. // acts as a proxy for the actual remote address, which is either a
  1134. // direct HTTP/HTTPS connection remote address, or in the case of
  1135. // downstream proxy of CDN fronts, some other value determined via
  1136. // HTTP headers.
  1137. func (conn *meekConn) RemoteAddr() net.Addr {
  1138. return conn.remoteAddr
  1139. }
  1140. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  1141. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  1142. // period. When it does, and the session is idle, the meekConn Read/Write will
  1143. // be interrupted and return an error (not a timeout error) before the deadline.
  1144. // In other words, this conn will approximate the desired functionality of
  1145. // timing out on idle on or before the requested deadline.
  1146. func (conn *meekConn) SetDeadline(t time.Time) error {
  1147. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  1148. if time.Now().Add(MEEK_MAX_SESSION_STALENESS).Before(t) {
  1149. return nil
  1150. }
  1151. return common.ContextError(errors.New("not supported"))
  1152. }
  1153. // Stub implementation of net.Conn.SetReadDeadline
  1154. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  1155. return common.ContextError(errors.New("not supported"))
  1156. }
  1157. // Stub implementation of net.Conn.SetWriteDeadline
  1158. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  1159. return common.ContextError(errors.New("not supported"))
  1160. }
  1161. // GetMetrics implements the common.MetricsSource interface. The metrics are
  1162. // maintained in the meek session type; but logTunnel, which calls
  1163. // MetricsSource.GetMetrics, has a pointer only to this conn, so it calls
  1164. // through to the session.
  1165. func (conn *meekConn) GetMetrics() common.LogFields {
  1166. return conn.meekSession.GetMetrics()
  1167. }