meek.go 60 KB

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