meek.go 38 KB

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