meek.go 55 KB

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