meek.go 46 KB

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