meek.go 60 KB

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