meek.go 46 KB

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