meek.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  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. }
  667. session.touch()
  668. // Create a new meek conn that will relay the payload
  669. // between meek request/responses and the tunnel server client
  670. // handler. The client IP is also used to initialize the
  671. // meek conn with a useful value to return when the tunnel
  672. // server calls conn.RemoteAddr() to get the client's IP address.
  673. // Assumes clientIP is a valid IP address; the port value is a stub
  674. // and is expected to be ignored.
  675. clientConn := newMeekConn(
  676. server,
  677. session,
  678. underlyingConn,
  679. &net.TCPAddr{
  680. IP: net.ParseIP(clientIP),
  681. Port: 0,
  682. },
  683. clientSessionData.MeekProtocolVersion)
  684. session.clientConn = clientConn
  685. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  686. // meek cookie to a session ID; v1 clients always send the
  687. // original meek cookie value with each request. The issue with
  688. // v1 is that clients which wake after a device sleep will attempt
  689. // to resume a meek session and the server can't differentiate
  690. // between resuming a session and creating a new session. This
  691. // causes the v1 client connection to hang/timeout.
  692. sessionID := meekCookie.Value
  693. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  694. sessionID, err = makeMeekSessionID()
  695. if err != nil {
  696. return "", nil, nil, "", nil, errors.Trace(err)
  697. }
  698. }
  699. server.sessionsLock.Lock()
  700. server.sessions[sessionID] = session
  701. server.sessionsLock.Unlock()
  702. // Note: from the tunnel server's perspective, this client connection
  703. // will close when session.delete calls Close() on the meekConn.
  704. server.clientHandler(clientSessionData.ClientTunnelProtocol, session.clientConn)
  705. return sessionID, session, underlyingConn, "", nil, nil
  706. }
  707. func (server *MeekServer) rateLimit(
  708. clientIP string, geoIPData GeoIPData, tunnelProtocol string) bool {
  709. historySize,
  710. thresholdSeconds,
  711. tunnelProtocols,
  712. regions,
  713. ISPs,
  714. ASNs,
  715. cities,
  716. GCTriggerCount, _, _ :=
  717. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  718. if historySize == 0 {
  719. return false
  720. }
  721. if len(tunnelProtocols) > 0 {
  722. if !common.Contains(tunnelProtocols, tunnelProtocol) {
  723. return false
  724. }
  725. }
  726. if len(regions) > 0 || len(ISPs) > 0 || len(ASNs) > 0 || len(cities) > 0 {
  727. if len(regions) > 0 {
  728. if !common.Contains(regions, geoIPData.Country) {
  729. return false
  730. }
  731. }
  732. if len(ISPs) > 0 {
  733. if !common.Contains(ISPs, geoIPData.ISP) {
  734. return false
  735. }
  736. }
  737. if len(ASNs) > 0 {
  738. if !common.Contains(ASNs, geoIPData.ASN) {
  739. return false
  740. }
  741. }
  742. if len(cities) > 0 {
  743. if !common.Contains(cities, geoIPData.City) {
  744. return false
  745. }
  746. }
  747. }
  748. // With IPv6, individual users or sites are users commonly allocated a /64
  749. // or /56, so rate limit by /56.
  750. rateLimitIP := clientIP
  751. IP := net.ParseIP(clientIP)
  752. if IP != nil && IP.To4() == nil {
  753. rateLimitIP = IP.Mask(net.CIDRMask(56, 128)).String()
  754. }
  755. // go-cache-lru is safe for concurrent access, but lacks an atomic
  756. // compare-and-set type operations to check if an entry exists before
  757. // adding a new one. This mutex ensures the Get and Add are atomic
  758. // (as well as synchronizing access to rateLimitCount).
  759. server.rateLimitLock.Lock()
  760. var rateLimiter *ratelimit.Bucket
  761. entry, ok := server.rateLimitHistory.Get(rateLimitIP)
  762. if ok {
  763. rateLimiter = entry.(*ratelimit.Bucket)
  764. } else {
  765. rateLimiter = ratelimit.NewBucketWithQuantum(
  766. time.Duration(thresholdSeconds)*time.Second,
  767. int64(historySize),
  768. int64(historySize))
  769. server.rateLimitHistory.Set(
  770. rateLimitIP,
  771. rateLimiter,
  772. time.Duration(thresholdSeconds)*time.Second)
  773. }
  774. limit := rateLimiter.TakeAvailable(1) < 1
  775. triggerGC := false
  776. if limit {
  777. server.rateLimitCount += 1
  778. if server.rateLimitCount >= GCTriggerCount {
  779. triggerGC = true
  780. server.rateLimitCount = 0
  781. }
  782. }
  783. server.rateLimitLock.Unlock()
  784. if triggerGC {
  785. select {
  786. case server.rateLimitSignalGC <- struct{}{}:
  787. default:
  788. }
  789. }
  790. return limit
  791. }
  792. func (server *MeekServer) rateLimitWorker() {
  793. for {
  794. select {
  795. case <-server.rateLimitSignalGC:
  796. runtime.GC()
  797. case <-server.stopBroadcast:
  798. return
  799. }
  800. }
  801. }
  802. func (server *MeekServer) deleteSession(sessionID string) {
  803. // Don't obtain the server.sessionsLock write lock until modifying
  804. // server.sessions, as the session.delete can block for up to
  805. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  806. // concurrently.
  807. //
  808. // Since a lock isn't held for the duration, concurrent calls to
  809. // deleteSession with the same sessionID could happen; this is
  810. // not expected since only the reaper goroutine calls deleteExpiredSessions
  811. // (and in any case concurrent execution of the ok block is not an issue).
  812. server.sessionsLock.RLock()
  813. session, ok := server.sessions[sessionID]
  814. server.sessionsLock.RUnlock()
  815. if ok {
  816. session.delete(false)
  817. server.sessionsLock.Lock()
  818. delete(server.sessions, sessionID)
  819. server.sessionsLock.Unlock()
  820. }
  821. }
  822. func (server *MeekServer) deleteExpiredSessions() {
  823. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  824. // so grab a snapshot list of expired sessions and do not hold a lock for
  825. // the duration of deleteExpiredSessions. This allows new sessions to be
  826. // added concurrently.
  827. //
  828. // New sessions added after the snapshot is taken will be checked for
  829. // expiry on subsequent periodic calls to deleteExpiredSessions.
  830. //
  831. // To avoid long delays in releasing resources, individual deletes are
  832. // performed concurrently.
  833. server.sessionsLock.Lock()
  834. expiredSessionIDs := make([]string, 0)
  835. for sessionID, session := range server.sessions {
  836. if session.expired() {
  837. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  838. }
  839. }
  840. server.sessionsLock.Unlock()
  841. start := time.Now()
  842. deleteWaitGroup := new(sync.WaitGroup)
  843. for _, sessionID := range expiredSessionIDs {
  844. deleteWaitGroup.Add(1)
  845. go func(sessionID string) {
  846. defer deleteWaitGroup.Done()
  847. server.deleteSession(sessionID)
  848. }(sessionID)
  849. }
  850. deleteWaitGroup.Wait()
  851. log.WithTraceFields(
  852. LogFields{"elapsed time": time.Since(start)}).Debug("deleted expired sessions")
  853. }
  854. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  855. // meek server.
  856. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  857. switch connState {
  858. case http.StateNew:
  859. server.openConns.Add(conn)
  860. case http.StateHijacked, http.StateClosed:
  861. server.openConns.Remove(conn)
  862. }
  863. }
  864. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  865. // payload is base64 encoded, obfuscated, and NaCl encrypted.
  866. func (server *MeekServer) getMeekCookiePayload(
  867. clientIP string, cookieValue string) ([]byte, error) {
  868. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  869. if err != nil {
  870. return nil, errors.Trace(err)
  871. }
  872. // The data consists of an obfuscated seed message prepended
  873. // to the obfuscated, encrypted payload. The server obfuscator
  874. // will read the seed message, leaving the remaining encrypted
  875. // data in the reader.
  876. reader := bytes.NewReader(decodedValue[:])
  877. obfuscator, err := obfuscator.NewServerObfuscator(
  878. &obfuscator.ObfuscatorConfig{
  879. Keyword: server.support.Config.MeekObfuscatedKey,
  880. SeedHistory: server.obfuscatorSeedHistory,
  881. IrregularLogger: func(clientIP string, err error, logFields common.LogFields) {
  882. logIrregularTunnel(
  883. server.support,
  884. server.listenerTunnelProtocol,
  885. server.listenerPort,
  886. clientIP,
  887. errors.Trace(err),
  888. LogFields(logFields))
  889. },
  890. },
  891. clientIP,
  892. reader)
  893. if err != nil {
  894. return nil, errors.Trace(err)
  895. }
  896. offset, err := reader.Seek(0, 1)
  897. if err != nil {
  898. return nil, errors.Trace(err)
  899. }
  900. encryptedPayload := decodedValue[offset:]
  901. obfuscator.ObfuscateClientToServer(encryptedPayload)
  902. var nonce [24]byte
  903. var privateKey, ephemeralPublicKey [32]byte
  904. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  905. server.support.Config.MeekCookieEncryptionPrivateKey)
  906. if err != nil {
  907. return nil, errors.Trace(err)
  908. }
  909. copy(privateKey[:], decodedPrivateKey)
  910. if len(encryptedPayload) < 32 {
  911. return nil, errors.TraceNew("unexpected encrypted payload size")
  912. }
  913. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  914. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  915. if !ok {
  916. return nil, errors.TraceNew("open box failed")
  917. }
  918. return payload, nil
  919. }
  920. // makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
  921. // Currently, this config is optimized for fronted meek where the nature
  922. // of the connection is non-circumvention; it's optimized for performance
  923. // assuming the peer is an uncensored CDN.
  924. func (server *MeekServer) makeMeekTLSConfig(
  925. isFronted bool, useObfuscatedSessionTickets bool) (*tris.Config, error) {
  926. certificate, privateKey, err := common.GenerateWebServerCertificate(values.GetHostName())
  927. if err != nil {
  928. return nil, errors.Trace(err)
  929. }
  930. tlsCertificate, err := tris.X509KeyPair(
  931. []byte(certificate), []byte(privateKey))
  932. if err != nil {
  933. return nil, errors.Trace(err)
  934. }
  935. // Vary the minimum version to frustrate scanning/fingerprinting of unfronted servers.
  936. // Limitation: like the certificate, this value changes on restart.
  937. minVersionCandidates := []uint16{tris.VersionTLS10, tris.VersionTLS11, tris.VersionTLS12}
  938. minVersion := minVersionCandidates[prng.Intn(len(minVersionCandidates))]
  939. config := &tris.Config{
  940. Certificates: []tris.Certificate{tlsCertificate},
  941. NextProtos: []string{"http/1.1"},
  942. MinVersion: minVersion,
  943. UseExtendedMasterSecret: true,
  944. }
  945. if isFronted {
  946. // This is a reordering of the supported CipherSuites in golang 1.6[*]. Non-ephemeral key
  947. // CipherSuites greatly reduce server load, and we try to select these since the meek
  948. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  949. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  950. // by ephemeral key CipherSuites.
  951. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  952. //
  953. // This optimization is applied only when there's a CDN in front of the meek server; in
  954. // unfronted cases we prefer a more natural TLS handshake.
  955. //
  956. // [*] the list has since been updated, removing CipherSuites using RC4 and 3DES.
  957. config.CipherSuites = []uint16{
  958. tris.TLS_RSA_WITH_AES_128_GCM_SHA256,
  959. tris.TLS_RSA_WITH_AES_256_GCM_SHA384,
  960. tris.TLS_RSA_WITH_AES_128_CBC_SHA,
  961. tris.TLS_RSA_WITH_AES_256_CBC_SHA,
  962. tris.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  963. tris.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  964. tris.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  965. tris.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  966. tris.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  967. tris.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  968. tris.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  969. tris.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  970. }
  971. config.PreferServerCipherSuites = true
  972. }
  973. if useObfuscatedSessionTickets {
  974. // See obfuscated session ticket overview
  975. // in NewObfuscatedClientSessionCache.
  976. config.UseObfuscatedSessionTickets = true
  977. var obfuscatedSessionTicketKey [32]byte
  978. key, err := hex.DecodeString(server.support.Config.MeekObfuscatedKey)
  979. if err == nil && len(key) != 32 {
  980. err = std_errors.New("invalid obfuscated session key length")
  981. }
  982. if err != nil {
  983. return nil, errors.Trace(err)
  984. }
  985. copy(obfuscatedSessionTicketKey[:], key)
  986. var standardSessionTicketKey [32]byte
  987. _, err = rand.Read(standardSessionTicketKey[:])
  988. if err != nil {
  989. return nil, errors.Trace(err)
  990. }
  991. // Note: SessionTicketKey needs to be set, or else, it appears,
  992. // tris.Config.serverInit() will clobber the value set by
  993. // SetSessionTicketKeys.
  994. config.SessionTicketKey = obfuscatedSessionTicketKey
  995. config.SetSessionTicketKeys([][32]byte{
  996. standardSessionTicketKey,
  997. obfuscatedSessionTicketKey})
  998. }
  999. // When configured, initialize passthrough mode, an anti-probing defense.
  1000. // Clients must prove knowledge of the obfuscated key via a message sent in
  1001. // the TLS ClientHello random field.
  1002. //
  1003. // When clients fail to provide a valid message, the client connection is
  1004. // relayed to the designated passthrough address, typically another web site.
  1005. // The entire flow is relayed, including the original ClientHello, so the
  1006. // client will perform a TLS handshake with the passthrough target.
  1007. //
  1008. // Irregular events are logged for invalid client activity.
  1009. if server.passthroughAddress != "" {
  1010. config.PassthroughAddress = server.passthroughAddress
  1011. config.PassthroughVerifyMessage = func(
  1012. message []byte) bool {
  1013. return obfuscator.VerifyTLSPassthroughMessage(
  1014. !server.support.Config.LegacyPassthrough,
  1015. server.support.Config.MeekObfuscatedKey,
  1016. message)
  1017. }
  1018. config.PassthroughLogInvalidMessage = func(
  1019. clientIP string) {
  1020. logIrregularTunnel(
  1021. server.support,
  1022. server.listenerTunnelProtocol,
  1023. server.listenerPort,
  1024. clientIP,
  1025. errors.TraceNew("invalid passthrough message"),
  1026. nil)
  1027. }
  1028. config.PassthroughHistoryAddNew = func(
  1029. clientIP string,
  1030. clientRandom []byte) bool {
  1031. // Use a custom, shorter TTL based on the validity period of the
  1032. // passthrough message.
  1033. TTL := obfuscator.TLS_PASSTHROUGH_TIME_PERIOD
  1034. if server.support.Config.LegacyPassthrough {
  1035. TTL = obfuscator.HISTORY_SEED_TTL
  1036. }
  1037. // strictMode is true as, unlike with meek cookies, legitimate meek clients
  1038. // never retry TLS connections using a previous random value.
  1039. ok, logFields := server.obfuscatorSeedHistory.AddNewWithTTL(
  1040. true,
  1041. clientIP,
  1042. "client-random",
  1043. clientRandom,
  1044. TTL)
  1045. if logFields != nil {
  1046. logIrregularTunnel(
  1047. server.support,
  1048. server.listenerTunnelProtocol,
  1049. server.listenerPort,
  1050. clientIP,
  1051. errors.TraceNew("duplicate passthrough message"),
  1052. LogFields(*logFields))
  1053. }
  1054. return ok
  1055. }
  1056. }
  1057. return config, nil
  1058. }
  1059. type meekSession struct {
  1060. // Note: 64-bit ints used with atomic operations are placed
  1061. // at the start of struct to ensure 64-bit alignment.
  1062. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  1063. lastActivity int64
  1064. requestCount int64
  1065. metricClientRetries int64
  1066. metricPeakResponseSize int64
  1067. metricPeakCachedResponseSize int64
  1068. metricPeakCachedResponseHitSize int64
  1069. metricCachedResponseMissPosition int64
  1070. metricUnderlyingConnCount int64
  1071. lock sync.Mutex
  1072. deleted bool
  1073. underlyingConn net.Conn
  1074. clientConn *meekConn
  1075. meekProtocolVersion int
  1076. sessionIDSent bool
  1077. cachedResponse *CachedResponse
  1078. }
  1079. func (session *meekSession) touch() {
  1080. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  1081. }
  1082. func (session *meekSession) expired() bool {
  1083. if session.clientConn == nil {
  1084. // Not fully initialized. meekSession.clientConn will be set before adding
  1085. // the session to MeekServer.sessions.
  1086. return false
  1087. }
  1088. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  1089. return monotime.Since(lastActivity) >
  1090. session.clientConn.meekServer.maxSessionStaleness
  1091. }
  1092. // delete releases all resources allocated by a session.
  1093. func (session *meekSession) delete(haveLock bool) {
  1094. // TODO: close the persistent HTTP client connection, if one exists?
  1095. // This final call session.cachedResponse.Reset releases shared resources.
  1096. //
  1097. // This call requires exclusive access. session.lock is be obtained before
  1098. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  1099. // request for this session is being processed concurrently, and pending
  1100. // requests will block at session.lock.
  1101. //
  1102. // This logic assumes that no further session.cachedResponse access occurs,
  1103. // or else resources may deplete (buffers won't be returned to the pool).
  1104. // These requirements are achieved by obtaining the lock, setting
  1105. // session.deleted, and any subsequent request handlers checking
  1106. // session.deleted immediately after obtaining the lock.
  1107. //
  1108. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  1109. // the timeout for any active request handler processing a session
  1110. // request.
  1111. //
  1112. // When the lock must be acquired, clientConn.Close is called first, to
  1113. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  1114. session.clientConn.Close()
  1115. if !haveLock {
  1116. session.lock.Lock()
  1117. }
  1118. // Release all extended buffers back to the pool.
  1119. // session.cachedResponse.Reset is not safe for concurrent calls.
  1120. session.cachedResponse.Reset()
  1121. session.deleted = true
  1122. if !haveLock {
  1123. session.lock.Unlock()
  1124. }
  1125. }
  1126. // GetMetrics implements the common.MetricsSource interface.
  1127. func (session *meekSession) GetMetrics() common.LogFields {
  1128. logFields := make(common.LogFields)
  1129. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  1130. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  1131. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  1132. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  1133. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  1134. logFields["meek_underlying_connection_count"] = atomic.LoadInt64(&session.metricUnderlyingConnCount)
  1135. return logFields
  1136. }
  1137. // makeMeekSessionID creates a new session ID. The variable size is intended to
  1138. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  1139. func makeMeekSessionID() (string, error) {
  1140. size := MEEK_MIN_SESSION_ID_LENGTH +
  1141. prng.Intn(MEEK_MAX_SESSION_ID_LENGTH-MEEK_MIN_SESSION_ID_LENGTH)
  1142. sessionID, err := common.MakeSecureRandomBytes(size)
  1143. if err != nil {
  1144. return "", errors.Trace(err)
  1145. }
  1146. // Omit padding to maximize variable size space. To the client, the session
  1147. // ID is an opaque string cookie value.
  1148. return base64.RawStdEncoding.EncodeToString(sessionID), nil
  1149. }
  1150. // meekConn implements the net.Conn interface and is to be used as a client
  1151. // connection by the tunnel server (being passed to sshServer.handleClient).
  1152. // meekConn bridges net/http request/response payload readers and writers
  1153. // and goroutines calling Read()s and Write()s.
  1154. type meekConn struct {
  1155. meekServer *MeekServer
  1156. meekSession *meekSession
  1157. firstUnderlyingConn net.Conn
  1158. remoteAddr net.Addr
  1159. protocolVersion int
  1160. closeBroadcast chan struct{}
  1161. closed int32
  1162. lastReadChecksum *uint64
  1163. readLock sync.Mutex
  1164. emptyReadBuffer chan *bytes.Buffer
  1165. partialReadBuffer chan *bytes.Buffer
  1166. fullReadBuffer chan *bytes.Buffer
  1167. writeLock sync.Mutex
  1168. nextWriteBuffer chan []byte
  1169. writeResult chan error
  1170. }
  1171. func newMeekConn(
  1172. meekServer *MeekServer,
  1173. meekSession *meekSession,
  1174. underlyingConn net.Conn,
  1175. remoteAddr net.Addr,
  1176. protocolVersion int) *meekConn {
  1177. // In order to inspect its properties, meekConn will hold a reference to
  1178. // firstUnderlyingConn, the _first_ underlying TCP conn, for the full
  1179. // lifetime of meekConn, which may exceed the lifetime of firstUnderlyingConn
  1180. // and include subsequent underlying TCP conns. In this case, it is expected
  1181. // that firstUnderlyingConn will be closed by "net/http", so no OS resources
  1182. // (e.g., a socket) are retained longer than necessary.
  1183. conn := &meekConn{
  1184. meekServer: meekServer,
  1185. meekSession: meekSession,
  1186. firstUnderlyingConn: underlyingConn,
  1187. remoteAddr: remoteAddr,
  1188. protocolVersion: protocolVersion,
  1189. closeBroadcast: make(chan struct{}),
  1190. closed: 0,
  1191. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  1192. partialReadBuffer: make(chan *bytes.Buffer, 1),
  1193. fullReadBuffer: make(chan *bytes.Buffer, 1),
  1194. nextWriteBuffer: make(chan []byte, 1),
  1195. writeResult: make(chan error, 1),
  1196. }
  1197. // Read() calls and pumpReads() are synchronized by exchanging control
  1198. // of a single readBuffer. This is the same scheme used in and described
  1199. // in psiphon.MeekConn.
  1200. conn.emptyReadBuffer <- new(bytes.Buffer)
  1201. return conn
  1202. }
  1203. // GetMetrics implements the common.MetricsSource interface. The metrics are
  1204. // maintained in the meek session type; but logTunnel, which calls
  1205. // MetricsSource.GetMetrics, has a pointer only to this conn, so it calls
  1206. // through to the session.
  1207. func (conn *meekConn) GetMetrics() common.LogFields {
  1208. logFields := conn.meekSession.GetMetrics()
  1209. if conn.meekServer.passthroughAddress != "" {
  1210. logFields["passthrough_address"] = conn.meekServer.passthroughAddress
  1211. }
  1212. // Include metrics, such as fragmentor metrics, from the _first_ underlying
  1213. // TCP conn. Properties of subsequent underlying TCP conns are not reflected
  1214. // in these metrics; we assume that the first TCP conn, which most likely
  1215. // transits the various protocol handshakes, is most significant.
  1216. underlyingMetrics, ok := conn.firstUnderlyingConn.(common.MetricsSource)
  1217. if ok {
  1218. logFields.Add(underlyingMetrics.GetMetrics())
  1219. }
  1220. return logFields
  1221. }
  1222. // GetUnderlyingTCPAddrs implements the common.UnderlyingTCPAddrSource
  1223. // interface, returning the TCP addresses for the _first_ underlying TCP
  1224. // connection in the meek tunnel.
  1225. func (conn *meekConn) GetUnderlyingTCPAddrs() (*net.TCPAddr, *net.TCPAddr, bool) {
  1226. localAddr, ok := conn.firstUnderlyingConn.LocalAddr().(*net.TCPAddr)
  1227. if !ok {
  1228. return nil, nil, false
  1229. }
  1230. remoteAddr, ok := conn.firstUnderlyingConn.RemoteAddr().(*net.TCPAddr)
  1231. if !ok {
  1232. return nil, nil, false
  1233. }
  1234. return localAddr, remoteAddr, true
  1235. }
  1236. // SetReplay implements the common.FragmentorReplayAccessor interface, applying
  1237. // the inputs to the _first_ underlying TCP connection in the meek tunnel. If
  1238. // the underlying connection is closed, the SetSeed call will have no effect.
  1239. func (conn *meekConn) SetReplay(PRNG *prng.PRNG) {
  1240. fragmentor, ok := conn.firstUnderlyingConn.(common.FragmentorReplayAccessor)
  1241. if ok {
  1242. fragmentor.SetReplay(PRNG)
  1243. }
  1244. }
  1245. // GetReplay implements the FragmentorReplayAccessor interface, getting the
  1246. // outputs from the _first_ underlying TCP connection in the meek tunnel.
  1247. //
  1248. // We assume that the first TCP conn is most significant: the initial TCP
  1249. // connection most likely fragments protocol handshakes; and, in the case the
  1250. // packet manipulation, any selected packet manipulation spec would have been
  1251. // successful.
  1252. func (conn *meekConn) GetReplay() (*prng.Seed, bool) {
  1253. fragmentor, ok := conn.firstUnderlyingConn.(common.FragmentorReplayAccessor)
  1254. if ok {
  1255. return fragmentor.GetReplay()
  1256. }
  1257. return nil, false
  1258. }
  1259. // pumpReads causes goroutines blocking on meekConn.Read() to read
  1260. // from the specified reader. This function blocks until the reader
  1261. // is fully consumed or the meekConn is closed. A read buffer allows
  1262. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  1263. // without a Read() immediately consuming the bytes, but there's still
  1264. // a possibility of a stall if no Read() calls are made after this
  1265. // read buffer is full.
  1266. // Returns the number of request bytes read.
  1267. // Note: assumes only one concurrent call to pumpReads
  1268. func (conn *meekConn) pumpReads(reader io.Reader) (int64, error) {
  1269. // Use either an empty or partial buffer. By using a partial
  1270. // buffer, pumpReads will not block if the Read() caller has
  1271. // not fully drained the read buffer.
  1272. var readBuffer *bytes.Buffer
  1273. select {
  1274. case readBuffer = <-conn.emptyReadBuffer:
  1275. case readBuffer = <-conn.partialReadBuffer:
  1276. case <-conn.closeBroadcast:
  1277. return 0, io.EOF
  1278. }
  1279. newDataOffset := readBuffer.Len()
  1280. // Since we need to read the full request payload in order to
  1281. // take its checksum before relaying it, the read buffer can
  1282. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  1283. // +1 allows for an explicit check for request payloads that
  1284. // exceed the maximum permitted length.
  1285. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  1286. n, err := readBuffer.ReadFrom(limitReader)
  1287. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  1288. err = std_errors.New("invalid request payload length")
  1289. }
  1290. // If the request read fails, don't relay the new data. This allows
  1291. // the client to retry and resend its request payload without
  1292. // interrupting/duplicating the payload flow.
  1293. if err != nil {
  1294. readBuffer.Truncate(newDataOffset)
  1295. conn.replaceReadBuffer(readBuffer)
  1296. return 0, errors.Trace(err)
  1297. }
  1298. // Check if request payload checksum matches immediately
  1299. // previous payload. On match, assume this is a client retry
  1300. // sending payload that was already relayed and skip this
  1301. // payload. Payload is OSSH ciphertext and almost surely
  1302. // will not repeat. In the highly unlikely case that it does,
  1303. // the underlying SSH connection will fail and the client
  1304. // must reconnect.
  1305. checksum := crc64.Checksum(
  1306. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  1307. if conn.lastReadChecksum == nil {
  1308. conn.lastReadChecksum = new(uint64)
  1309. } else if *conn.lastReadChecksum == checksum {
  1310. readBuffer.Truncate(newDataOffset)
  1311. }
  1312. *conn.lastReadChecksum = checksum
  1313. conn.replaceReadBuffer(readBuffer)
  1314. return n, nil
  1315. }
  1316. var errMeekConnectionHasClosed = std_errors.New("meek connection has closed")
  1317. // Read reads from the meekConn into buffer. Read blocks until
  1318. // some data is read or the meekConn closes. Under the hood, it
  1319. // waits for pumpReads to submit a reader to read from.
  1320. // Note: lock is to conform with net.Conn concurrency semantics
  1321. func (conn *meekConn) Read(buffer []byte) (int, error) {
  1322. conn.readLock.Lock()
  1323. defer conn.readLock.Unlock()
  1324. var readBuffer *bytes.Buffer
  1325. select {
  1326. case readBuffer = <-conn.partialReadBuffer:
  1327. case readBuffer = <-conn.fullReadBuffer:
  1328. case <-conn.closeBroadcast:
  1329. return 0, errors.Trace(errMeekConnectionHasClosed)
  1330. }
  1331. n, err := readBuffer.Read(buffer)
  1332. conn.replaceReadBuffer(readBuffer)
  1333. return n, err
  1334. }
  1335. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  1336. length := readBuffer.Len()
  1337. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1338. conn.fullReadBuffer <- readBuffer
  1339. } else if length == 0 {
  1340. conn.emptyReadBuffer <- readBuffer
  1341. } else {
  1342. conn.partialReadBuffer <- readBuffer
  1343. }
  1344. }
  1345. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  1346. // to the specified writer. This function blocks until the meek response
  1347. // body limits (size for protocol v1, turn around time for protocol v2+)
  1348. // are met, or the meekConn is closed.
  1349. //
  1350. // Note: channel scheme assumes only one concurrent call to pumpWrites
  1351. func (conn *meekConn) pumpWrites(
  1352. writer io.Writer, skipExtendedTurnAround bool) (int, error) {
  1353. startTime := time.Now()
  1354. timeout := time.NewTimer(conn.meekServer.turnAroundTimeout)
  1355. defer timeout.Stop()
  1356. n := 0
  1357. for {
  1358. select {
  1359. case buffer := <-conn.nextWriteBuffer:
  1360. written, err := writer.Write(buffer)
  1361. n += written
  1362. // Assumes that writeResult won't block.
  1363. // Note: always send the err to writeResult,
  1364. // as the Write() caller is blocking on this.
  1365. conn.writeResult <- err
  1366. if err != nil {
  1367. return n, err
  1368. }
  1369. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  1370. // Pre-protocol version 1 clients expect at most
  1371. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  1372. return n, nil
  1373. }
  1374. if skipExtendedTurnAround {
  1375. // When fast turn around is indicated, skip the extended turn
  1376. // around timeout. This optimizes for upstream flows.
  1377. return n, nil
  1378. }
  1379. totalElapsedTime := time.Since(startTime) / time.Millisecond
  1380. if totalElapsedTime >= conn.meekServer.extendedTurnAroundTimeout {
  1381. return n, nil
  1382. }
  1383. timeout.Reset(conn.meekServer.turnAroundTimeout)
  1384. case <-timeout.C:
  1385. return n, nil
  1386. case <-conn.closeBroadcast:
  1387. return n, errors.Trace(errMeekConnectionHasClosed)
  1388. }
  1389. }
  1390. }
  1391. // Write writes the buffer to the meekConn. It blocks until the
  1392. // entire buffer is written to or the meekConn closes. Under the
  1393. // hood, it waits for sufficient pumpWrites calls to consume the
  1394. // write buffer.
  1395. // Note: lock is to conform with net.Conn concurrency semantics
  1396. func (conn *meekConn) Write(buffer []byte) (int, error) {
  1397. conn.writeLock.Lock()
  1398. defer conn.writeLock.Unlock()
  1399. // TODO: may be more efficient to send whole buffer
  1400. // and have pumpWrites stash partial buffer when can't
  1401. // send it all.
  1402. n := 0
  1403. for n < len(buffer) {
  1404. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1405. if end > len(buffer) {
  1406. end = len(buffer)
  1407. }
  1408. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  1409. // to ensure compatibility with v1 protocol.
  1410. chunk := buffer[n:end]
  1411. select {
  1412. case conn.nextWriteBuffer <- chunk:
  1413. case <-conn.closeBroadcast:
  1414. return n, errors.Trace(errMeekConnectionHasClosed)
  1415. }
  1416. // Wait for the buffer to be processed.
  1417. select {
  1418. case <-conn.writeResult:
  1419. // The err from conn.writeResult comes from the
  1420. // io.MultiWriter used in pumpWrites, which writes
  1421. // to both the cached response and the HTTP response.
  1422. //
  1423. // Don't stop on error here, since only writing
  1424. // to the HTTP response will fail, and the client
  1425. // may retry and use the cached response.
  1426. //
  1427. // It's possible that the cached response buffer
  1428. // is too small for the client to successfully
  1429. // retry, but that cannot be determined. In this
  1430. // case, the meek connection will eventually fail.
  1431. //
  1432. // err is already logged in ServeHTTP.
  1433. case <-conn.closeBroadcast:
  1434. return n, errors.Trace(errMeekConnectionHasClosed)
  1435. }
  1436. n += len(chunk)
  1437. }
  1438. return n, nil
  1439. }
  1440. // Close closes the meekConn. This will interrupt any blocked
  1441. // Read, Write, pumpReads, and pumpWrites.
  1442. func (conn *meekConn) Close() error {
  1443. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  1444. close(conn.closeBroadcast)
  1445. // In general, we reply on "net/http" to close underlying TCP conns. In this
  1446. // case, we can directly close the first once, if it's still open.
  1447. conn.firstUnderlyingConn.Close()
  1448. }
  1449. return nil
  1450. }
  1451. // Stub implementation of net.Conn.LocalAddr
  1452. func (conn *meekConn) LocalAddr() net.Addr {
  1453. return nil
  1454. }
  1455. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  1456. // acts as a proxy for the actual remote address, which is either a
  1457. // direct HTTP/HTTPS connection remote address, or in the case of
  1458. // downstream proxy of CDN fronts, some other value determined via
  1459. // HTTP headers.
  1460. func (conn *meekConn) RemoteAddr() net.Addr {
  1461. return conn.remoteAddr
  1462. }
  1463. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  1464. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  1465. // period. When it does, and the session is idle, the meekConn Read/Write will
  1466. // be interrupted and return an error (not a timeout error) before the deadline.
  1467. // In other words, this conn will approximate the desired functionality of
  1468. // timing out on idle on or before the requested deadline.
  1469. func (conn *meekConn) SetDeadline(t time.Time) error {
  1470. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  1471. if time.Now().Add(conn.meekServer.maxSessionStaleness).Before(t) {
  1472. return nil
  1473. }
  1474. return errors.TraceNew("not supported")
  1475. }
  1476. // Stub implementation of net.Conn.SetReadDeadline
  1477. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  1478. return errors.TraceNew("not supported")
  1479. }
  1480. // Stub implementation of net.Conn.SetWriteDeadline
  1481. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  1482. return errors.TraceNew("not supported")
  1483. }