meek.go 46 KB

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