meek.go 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  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/subtle"
  25. "crypto/tls"
  26. "encoding/base64"
  27. "encoding/hex"
  28. "encoding/json"
  29. std_errors "errors"
  30. "hash/crc64"
  31. "io"
  32. "io/ioutil"
  33. "net"
  34. "net/http"
  35. "runtime"
  36. "strconv"
  37. "strings"
  38. "sync"
  39. "sync/atomic"
  40. "time"
  41. psiphon_tls "github.com/Psiphon-Labs/psiphon-tls"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/monotime"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  48. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  49. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  50. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  51. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  52. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  53. lrucache "github.com/cognusion/go-cache-lru"
  54. "github.com/juju/ratelimit"
  55. "golang.org/x/crypto/nacl/box"
  56. )
  57. // MeekServer is based on meek-server.go from Tor and Psiphon:
  58. //
  59. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  60. // CC0 1.0 Universal
  61. //
  62. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
  63. const (
  64. // Protocol version 1 clients can handle arbitrary length response bodies. Older clients
  65. // report no version number and expect at most 64K response bodies.
  66. MEEK_PROTOCOL_VERSION_1 = 1
  67. // Protocol version 2 clients initiate a session by sending an encrypted and obfuscated meek
  68. // cookie with their initial HTTP request. Connection information is contained within the
  69. // encrypted cookie payload. The server inspects the cookie and establishes a new session and
  70. // returns a new random session ID back to client via Set-Cookie header. The client uses this
  71. // session ID on all subsequent requests for the remainder of the session.
  72. MEEK_PROTOCOL_VERSION_2 = 2
  73. // Protocol version 3 clients include resiliency enhancements and will add a Range header
  74. // when retrying a request for a partially downloaded response payload.
  75. MEEK_PROTOCOL_VERSION_3 = 3
  76. MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  77. MEEK_MIN_SESSION_ID_LENGTH = 8
  78. MEEK_MAX_SESSION_ID_LENGTH = 20
  79. MEEK_DEFAULT_TURN_AROUND_TIMEOUT = 10 * time.Millisecond
  80. MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT = 100 * time.Millisecond
  81. MEEK_DEFAULT_SKIP_EXTENDED_TURN_AROUND_THRESHOLD = 8192
  82. MEEK_DEFAULT_MAX_SESSION_STALENESS = 45 * time.Second
  83. MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT = 45 * time.Second
  84. MEEK_DEFAULT_FRONTED_HTTP_CLIENT_IO_TIMEOUT = 360 * time.Second
  85. MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH = 65536
  86. MEEK_DEFAULT_POOL_BUFFER_LENGTH = 65536
  87. MEEK_DEFAULT_POOL_BUFFER_COUNT = 2048
  88. MEEK_ENDPOINT_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  89. )
  90. // MeekServer implements the meek protocol, which tunnels TCP traffic (in the case of Psiphon,
  91. // Obfuscated SSH traffic) over HTTP. Meek may be fronted (through a CDN) or direct and may be
  92. // HTTP or HTTPS.
  93. //
  94. // Upstream traffic arrives in HTTP request bodies and downstream traffic is sent in response
  95. // bodies. The sequence of traffic for a given flow is associated using a session ID that's
  96. // set as a HTTP cookie for the client to submit with each request.
  97. //
  98. // MeekServer hooks into TunnelServer via the net.Conn interface by transforming the
  99. // HTTP payload traffic for a given session into net.Conn conforming Read()s and Write()s via
  100. // the meekConn struct.
  101. type MeekServer struct {
  102. support *SupportServices
  103. listener net.Listener
  104. listenerTunnelProtocol string
  105. listenerPort int
  106. isFronted bool
  107. passthroughAddress string
  108. turnAroundTimeout time.Duration
  109. extendedTurnAroundTimeout time.Duration
  110. skipExtendedTurnAroundThreshold int
  111. maxSessionStaleness time.Duration
  112. httpClientIOTimeout time.Duration
  113. stdTLSConfig *tls.Config
  114. psiphonTLSConfig *psiphon_tls.Config
  115. obfuscatorSeedHistory *obfuscator.SeedHistory
  116. clientHandler func(clientConn net.Conn, data *additionalTransportData)
  117. openConns *common.Conns
  118. stopBroadcast <-chan struct{}
  119. sessionsLock sync.RWMutex
  120. sessions map[string]*meekSession
  121. checksumTable *crc64.Table
  122. bufferPool *CachedResponseBufferPool
  123. rateLimitLock sync.Mutex
  124. rateLimitHistory *lrucache.Cache
  125. rateLimitCount int
  126. rateLimitSignalGC chan struct{}
  127. normalizer *transforms.HTTPNormalizerListener
  128. inproxyBroker *inproxy.Broker
  129. }
  130. // NewMeekServer initializes a new meek server.
  131. func NewMeekServer(
  132. support *SupportServices,
  133. listener net.Listener,
  134. listenerTunnelProtocol string,
  135. listenerPort int,
  136. useTLS, isFronted, useObfuscatedSessionTickets, useHTTPNormalizer bool,
  137. clientHandler func(clientConn net.Conn, data *additionalTransportData),
  138. stopBroadcast <-chan struct{}) (*MeekServer, error) {
  139. // With fronting, MeekRequiredHeaders can be used to ensure that the
  140. // request is coming through a CDN that's configured to add the
  141. // specified, secret header values. Configuring the MeekRequiredHeaders
  142. // scheme is required when running an in-proxy broker.
  143. if isFronted &&
  144. support.Config.MeekServerRunInproxyBroker &&
  145. len(support.Config.MeekRequiredHeaders) < 1 {
  146. return nil, errors.TraceNew("missing required header")
  147. }
  148. passthroughAddress := support.Config.TunnelProtocolPassthroughAddresses[listenerTunnelProtocol]
  149. turnAroundTimeout := MEEK_DEFAULT_TURN_AROUND_TIMEOUT
  150. if support.Config.MeekTurnAroundTimeoutMilliseconds != nil {
  151. turnAroundTimeout = time.Duration(
  152. *support.Config.MeekTurnAroundTimeoutMilliseconds) * time.Millisecond
  153. }
  154. extendedTurnAroundTimeout := MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT
  155. if support.Config.MeekExtendedTurnAroundTimeoutMilliseconds != nil {
  156. extendedTurnAroundTimeout = time.Duration(
  157. *support.Config.MeekExtendedTurnAroundTimeoutMilliseconds) * time.Millisecond
  158. }
  159. skipExtendedTurnAroundThreshold := MEEK_DEFAULT_SKIP_EXTENDED_TURN_AROUND_THRESHOLD
  160. if support.Config.MeekSkipExtendedTurnAroundThresholdBytes != nil {
  161. skipExtendedTurnAroundThreshold = *support.Config.MeekSkipExtendedTurnAroundThresholdBytes
  162. }
  163. maxSessionStaleness := MEEK_DEFAULT_MAX_SESSION_STALENESS
  164. if support.Config.MeekMaxSessionStalenessMilliseconds != nil {
  165. maxSessionStaleness = time.Duration(
  166. *support.Config.MeekMaxSessionStalenessMilliseconds) * time.Millisecond
  167. }
  168. var httpClientIOTimeout time.Duration
  169. if isFronted {
  170. // Fronted has a distinct timeout, and the default is higher since new
  171. // clients may connect to a CDN edge and start using an existing
  172. // persistent connection.
  173. httpClientIOTimeout = MEEK_DEFAULT_FRONTED_HTTP_CLIENT_IO_TIMEOUT
  174. if support.Config.MeekFrontedHTTPClientIOTimeoutMilliseconds != nil {
  175. httpClientIOTimeout = time.Duration(
  176. *support.Config.MeekFrontedHTTPClientIOTimeoutMilliseconds) * time.Millisecond
  177. }
  178. } else {
  179. httpClientIOTimeout = MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT
  180. if support.Config.MeekHTTPClientIOTimeoutMilliseconds != nil {
  181. httpClientIOTimeout = time.Duration(
  182. *support.Config.MeekHTTPClientIOTimeoutMilliseconds) * time.Millisecond
  183. }
  184. }
  185. checksumTable := crc64.MakeTable(crc64.ECMA)
  186. bufferLength := MEEK_DEFAULT_POOL_BUFFER_LENGTH
  187. if support.Config.MeekCachedResponsePoolBufferSize != 0 {
  188. bufferLength = support.Config.MeekCachedResponsePoolBufferSize
  189. }
  190. bufferCount := MEEK_DEFAULT_POOL_BUFFER_COUNT
  191. if support.Config.MeekCachedResponsePoolBufferCount != 0 {
  192. bufferCount = support.Config.MeekCachedResponsePoolBufferCount
  193. }
  194. _, thresholdSeconds, _, _, _, _, _, _, reapFrequencySeconds, maxEntries :=
  195. support.TrafficRulesSet.GetMeekRateLimiterConfig()
  196. rateLimitHistory := lrucache.NewWithLRU(
  197. time.Duration(thresholdSeconds)*time.Second,
  198. time.Duration(reapFrequencySeconds)*time.Second,
  199. maxEntries)
  200. bufferPool := NewCachedResponseBufferPool(bufferLength, bufferCount)
  201. meekServer := &MeekServer{
  202. support: support,
  203. listener: listener,
  204. listenerTunnelProtocol: listenerTunnelProtocol,
  205. listenerPort: listenerPort,
  206. isFronted: isFronted,
  207. passthroughAddress: passthroughAddress,
  208. turnAroundTimeout: turnAroundTimeout,
  209. extendedTurnAroundTimeout: extendedTurnAroundTimeout,
  210. skipExtendedTurnAroundThreshold: skipExtendedTurnAroundThreshold,
  211. maxSessionStaleness: maxSessionStaleness,
  212. httpClientIOTimeout: httpClientIOTimeout,
  213. obfuscatorSeedHistory: obfuscator.NewSeedHistory(nil),
  214. clientHandler: clientHandler,
  215. openConns: common.NewConns(),
  216. stopBroadcast: stopBroadcast,
  217. sessions: make(map[string]*meekSession),
  218. checksumTable: checksumTable,
  219. bufferPool: bufferPool,
  220. rateLimitHistory: rateLimitHistory,
  221. rateLimitSignalGC: make(chan struct{}, 1),
  222. }
  223. if useTLS {
  224. // For fronted meek servers, crypto/tls is used to ensure that
  225. // net/http.Server.Serve will find *crypto/tls.Conn types, as
  226. // required for enabling HTTP/2. The fronted case does not not
  227. // support or require the TLS passthrough or obfuscated session
  228. // ticket mechanisms, which are implemented in psiphon-tls. HTTP/2 is
  229. // preferred for fronted meek servers in order to multiplex many
  230. // concurrent requests, either from many tunnel clients or
  231. // many/individual in-proxy broker clients, over a single network
  232. // connection.
  233. //
  234. // For direct meek servers, psiphon-tls is used to provide the TLS
  235. // passthrough or obfuscated session ticket obfuscation mechanisms.
  236. // Direct meek servers do not enable HTTP/1.1 Each individual meek
  237. // tunnel client will have its own network connection and each client
  238. // has only a single in-flight meek request at a time.
  239. if isFronted {
  240. if useObfuscatedSessionTickets {
  241. return nil, errors.TraceNew("obfuscated session tickets unsupported")
  242. }
  243. if meekServer.passthroughAddress != "" {
  244. return nil, errors.TraceNew("passthrough unsupported")
  245. }
  246. tlsConfig, err := meekServer.makeFrontedMeekTLSConfig()
  247. if err != nil {
  248. return nil, errors.Trace(err)
  249. }
  250. meekServer.stdTLSConfig = tlsConfig
  251. } else {
  252. tlsConfig, err := meekServer.makeDirectMeekTLSConfig(
  253. useObfuscatedSessionTickets)
  254. if err != nil {
  255. return nil, errors.Trace(err)
  256. }
  257. meekServer.psiphonTLSConfig = tlsConfig
  258. }
  259. }
  260. if useHTTPNormalizer && protocol.TunnelProtocolUsesMeekHTTPNormalizer(listenerTunnelProtocol) {
  261. normalizer := meekServer.makeMeekHTTPNormalizerListener()
  262. meekServer.normalizer = normalizer
  263. meekServer.listener = normalizer
  264. }
  265. // Initialize in-proxy broker service
  266. if support.Config.MeekServerRunInproxyBroker {
  267. if support.Config.InproxyBrokerAllowCommonASNMatching {
  268. inproxy.SetAllowCommonASNMatching(true)
  269. }
  270. sessionPrivateKey, err := inproxy.SessionPrivateKeyFromString(
  271. support.Config.InproxyBrokerSessionPrivateKey)
  272. if err != nil {
  273. return nil, errors.Trace(err)
  274. }
  275. obfuscationRootSecret, err := inproxy.ObfuscationSecretFromString(
  276. support.Config.InproxyBrokerObfuscationRootSecret)
  277. if err != nil {
  278. return nil, errors.Trace(err)
  279. }
  280. lookupGeoIPData := func(IP string) common.GeoIPData {
  281. return common.GeoIPData(support.GeoIPService.Lookup(IP))
  282. }
  283. inproxyBroker, err := inproxy.NewBroker(
  284. &inproxy.BrokerConfig{
  285. Logger: CommonLogger(log),
  286. AllowProxy: meekServer.inproxyBrokerAllowProxy,
  287. AllowClient: meekServer.inproxyBrokerAllowClient,
  288. AllowDomainFrontedDestinations: meekServer.inproxyBrokerAllowDomainFrontedDestinations,
  289. LookupGeoIP: lookupGeoIPData,
  290. APIParameterValidator: getInproxyBrokerAPIParameterValidator(support.Config),
  291. APIParameterLogFieldFormatter: getInproxyBrokerAPIParameterLogFieldFormatter(),
  292. IsValidServerEntryTag: support.PsinetDatabase.IsValidServerEntryTag,
  293. GetTactics: meekServer.inproxyBrokerGetTactics,
  294. PrivateKey: sessionPrivateKey,
  295. ObfuscationRootSecret: obfuscationRootSecret,
  296. ServerEntrySignaturePublicKey: support.Config.InproxyBrokerServerEntrySignaturePublicKey,
  297. })
  298. if err != nil {
  299. return nil, errors.Trace(err)
  300. }
  301. meekServer.inproxyBroker = inproxyBroker
  302. // inproxyReloadTactics initializes compartment ID, timeouts, and
  303. // other broker parameter values from tactics.
  304. err = meekServer.inproxyReloadTactics()
  305. if err != nil {
  306. return nil, errors.Trace(err)
  307. }
  308. }
  309. return meekServer, nil
  310. }
  311. // ReloadTactics signals components to reload tactics and reinitialize as
  312. // required when tactics may have changed.
  313. func (server *MeekServer) ReloadTactics() error {
  314. if server.support.Config.MeekServerRunInproxyBroker {
  315. err := server.inproxyReloadTactics()
  316. if err != nil {
  317. return errors.Trace(err)
  318. }
  319. }
  320. return nil
  321. }
  322. type meekContextKey struct {
  323. key string
  324. }
  325. var meekNetConnContextKey = &meekContextKey{"net.Conn"}
  326. // Run runs the meek server; this function blocks while serving HTTP or
  327. // HTTPS connections on the specified listener. This function also runs
  328. // a goroutine which cleans up expired meek client sessions.
  329. //
  330. // To stop the meek server, both Close() the listener and set the stopBroadcast
  331. // signal specified in NewMeekServer.
  332. func (server *MeekServer) Run() error {
  333. waitGroup := new(sync.WaitGroup)
  334. waitGroup.Add(1)
  335. go func() {
  336. defer waitGroup.Done()
  337. ticker := time.NewTicker(server.maxSessionStaleness / 2)
  338. defer ticker.Stop()
  339. for {
  340. select {
  341. case <-ticker.C:
  342. server.deleteExpiredSessions()
  343. case <-server.stopBroadcast:
  344. return
  345. }
  346. }
  347. }()
  348. waitGroup.Add(1)
  349. go func() {
  350. defer waitGroup.Done()
  351. server.rateLimitWorker()
  352. }()
  353. if server.inproxyBroker != nil {
  354. err := server.inproxyBroker.Start()
  355. if err != nil {
  356. return errors.Trace(err)
  357. }
  358. defer server.inproxyBroker.Stop()
  359. }
  360. // Serve HTTP or HTTPS
  361. //
  362. // - WriteTimeout may include time awaiting request, as per:
  363. // https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
  364. //
  365. // - Legacy meek-server wrapped each client HTTP connection with an explicit idle
  366. // timeout net.Conn and didn't use http.Server timeouts. We could do the same
  367. // here (use ActivityMonitoredConn) but the stock http.Server timeouts should
  368. // now be sufficient.
  369. //
  370. // - HTTP/2 is enabled (the default), which is required for efficient
  371. // in-proxy broker connection sharing.
  372. //
  373. // - Any CDN fronting a meek server running an in-proxy broker should be
  374. // configured with timeouts that accomodate the proxy announcement
  375. // request long polling.
  376. httpServer := &http.Server{
  377. ReadTimeout: server.httpClientIOTimeout,
  378. WriteTimeout: server.httpClientIOTimeout,
  379. Handler: server,
  380. ConnState: server.httpConnStateCallback,
  381. ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
  382. return context.WithValue(ctx, meekNetConnContextKey, conn)
  383. },
  384. }
  385. // Note: Serve() will be interrupted by server.listener.Close() call
  386. listener := server.listener
  387. if server.stdTLSConfig != nil {
  388. listener = tls.NewListener(server.listener, server.stdTLSConfig)
  389. } else if server.psiphonTLSConfig != nil {
  390. listener = psiphon_tls.NewListener(server.listener, server.psiphonTLSConfig)
  391. // Disable auto HTTP/2
  392. httpServer.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
  393. }
  394. err := httpServer.Serve(listener)
  395. // Can't check for the exact error that Close() will cause in Accept(),
  396. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  397. // explicit stop signal to stop gracefully.
  398. select {
  399. case <-server.stopBroadcast:
  400. err = nil
  401. default:
  402. }
  403. // deleteExpiredSessions calls deleteSession which may block waiting
  404. // for active request handlers to complete; timely shutdown requires
  405. // stopping the listener and closing all existing connections before
  406. // awaiting the reaperWaitGroup.
  407. server.listener.Close()
  408. server.openConns.CloseAll()
  409. waitGroup.Wait()
  410. return err
  411. }
  412. // ServeHTTP handles meek client HTTP requests, where the request body
  413. // contains upstream traffic and the response will contain downstream
  414. // traffic.
  415. func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
  416. // Note: no longer requiring that the request method is POST
  417. // Check for required headers and values. For fronting, required headers
  418. // may be used to identify a CDN edge. When this check fails,
  419. // TerminateHTTPConnection is called instead of handleError, so any
  420. // persistent connection is always closed.
  421. if len(server.support.Config.MeekRequiredHeaders) > 0 {
  422. for header, value := range server.support.Config.MeekRequiredHeaders {
  423. requestValue := request.Header.Get(header)
  424. // There's no ConstantTimeCompare for strings. While the
  425. // conversion from string to byte slice may leak the length of
  426. // the expected value, ConstantTimeCompare also takes time that's
  427. // a function of the length of the input byte slices; leaking the
  428. // expected value length isn't a vulnerability as long as the
  429. // secret is long enough and random.
  430. if subtle.ConstantTimeCompare([]byte(requestValue), []byte(value)) != 1 {
  431. log.WithTraceFields(LogFields{
  432. "header": header,
  433. "value": requestValue,
  434. }).Warning("invalid required meek header")
  435. common.TerminateHTTPConnection(responseWriter, request)
  436. return
  437. }
  438. }
  439. }
  440. // Check for the expected meek/session ID cookie. in-proxy broker requests
  441. // do not use or expect a meek cookie (the broker session protocol
  442. // encapsulated in the HTTP request/response payloads has its own
  443. // obfuscation and anti-replay mechanisms).
  444. //
  445. // TODO: log irregular tunnels for unexpected cookie cases?
  446. var meekCookie *http.Cookie
  447. for _, c := range request.Cookies() {
  448. meekCookie = c
  449. break
  450. }
  451. if (meekCookie == nil || len(meekCookie.Value) == 0) &&
  452. !server.support.Config.MeekServerRunInproxyBroker {
  453. log.WithTrace().Warning("missing meek cookie")
  454. common.TerminateHTTPConnection(responseWriter, request)
  455. return
  456. }
  457. if meekCookie != nil && server.support.Config.MeekServerInproxyBrokerOnly {
  458. log.WithTrace().Warning("unexpected meek cookie")
  459. common.TerminateHTTPConnection(responseWriter, request)
  460. return
  461. }
  462. // Check for prohibited HTTP headers.
  463. if len(server.support.Config.MeekProhibitedHeaders) > 0 {
  464. for _, header := range server.support.Config.MeekProhibitedHeaders {
  465. value := request.Header.Get(header)
  466. if header != "" {
  467. log.WithTraceFields(LogFields{
  468. "header": header,
  469. "value": value,
  470. }).Warning("prohibited meek header")
  471. server.handleError(responseWriter, request)
  472. return
  473. }
  474. }
  475. }
  476. // A valid meek cookie indicates which class of request this is:
  477. //
  478. // 1. A new meek session. Create a new session ID and proceed with
  479. // relaying tunnel traffic.
  480. //
  481. // 2. An existing meek session. Resume relaying tunnel traffic.
  482. //
  483. // 3. A request to an endpoint. This meek connection is not for relaying
  484. // tunnel traffic. Instead, the request is handed off to a custom handler.
  485. //
  486. // In the in-proxy broker case, there is no meek cookie, which avoids the
  487. // size and resource overhead of sending and processing a meek cookie
  488. // with each endpoint request.
  489. //
  490. // The broker session protocol encapsulated in the HTTP request/response
  491. // payloads has its own obfuscation and anti-replay mechanisms.
  492. //
  493. // In RunInproxyBroker mode, non-meek cookie requests are routed to the
  494. // in-proxy broker. getSessionOrEndpoint is still invoked in all cases,
  495. // to process GeoIP headers, invoke the meek rate limiter, etc.
  496. //
  497. // Limitations:
  498. //
  499. // - Adding arbirary cookies, as camouflage for plain HTTP for example, is
  500. // not supported.
  501. //
  502. // - the HTTP normalizer depends on the meek cookie
  503. // (see makeMeekHTTPNormalizerListener) so RunInproxyBroker mode is
  504. // incompatible with the HTTP normalizer.
  505. sessionID,
  506. session,
  507. underlyingConn,
  508. endPoint,
  509. endPointClientIP,
  510. endPointGeoIPData,
  511. err := server.getSessionOrEndpoint(request, meekCookie)
  512. if err != nil {
  513. // Debug since session cookie errors commonly occur during
  514. // normal operation.
  515. log.WithTraceFields(LogFields{"error": err}).Debug("session lookup failed")
  516. server.handleError(responseWriter, request)
  517. return
  518. }
  519. if endPoint != "" {
  520. // Route to endpoint handlers and return.
  521. handled := false
  522. switch endPoint {
  523. case tactics.TACTICS_END_POINT, tactics.SPEED_TEST_END_POINT:
  524. handled = server.support.TacticsServer.HandleEndPoint(
  525. endPoint,
  526. common.GeoIPData(*endPointGeoIPData),
  527. responseWriter,
  528. request)
  529. // Currently, TacticsServer.HandleEndPoint handles returning a 404 instead
  530. // leaving that up to server.handleError.
  531. //
  532. // TODO: call server.handleError, for its isFronting special case.
  533. case inproxy.BrokerEndPointName:
  534. handled = true
  535. err := server.inproxyBrokerHandler(
  536. endPointClientIP,
  537. common.GeoIPData(*endPointGeoIPData),
  538. responseWriter,
  539. request)
  540. if err != nil {
  541. log.WithTraceFields(LogFields{"error": err}).Warning("inproxyBrokerHandler failed")
  542. server.handleError(responseWriter, request)
  543. }
  544. }
  545. if !handled {
  546. log.WithTraceFields(LogFields{"endPoint": endPoint}).Warning("unhandled endpoint")
  547. server.handleError(responseWriter, request)
  548. }
  549. return
  550. }
  551. // Tunnel relay mode.
  552. // Ensure that there's only one concurrent request handler per client
  553. // session. Depending on the nature of a network disruption, it can
  554. // happen that a client detects a failure and retries while the server
  555. // is still streaming response in the handler for the _previous_ client
  556. // request.
  557. //
  558. // Even if the session.cachedResponse were safe for concurrent
  559. // use (it is not), concurrent handling could lead to loss of session
  560. // since upstream data read by the first request may not reach the
  561. // cached response before the second request reads the cached data.
  562. //
  563. // The existing handler will stream response data, holding the lock,
  564. // for no more than MEEK_EXTENDED_TURN_AROUND_TIMEOUT.
  565. //
  566. // TODO: interrupt an existing handler? The existing handler will be
  567. // sending data to the cached response, but if that buffer fills, the
  568. // session will be lost.
  569. requestNumber := atomic.AddInt64(&session.requestCount, 1)
  570. // Wait for the existing request to complete.
  571. session.lock.Lock()
  572. defer session.lock.Unlock()
  573. // Count this metric once the lock is acquired, to avoid concurrent and
  574. // potentially incorrect session.underlyingConn updates.
  575. //
  576. // It should never be the case that a new underlyingConn has the same
  577. // value as the previous session.underlyingConn, as each is a net.Conn
  578. // interface which includes a pointer, and the previous value cannot
  579. // be garbage collected until session.underlyingConn is updated.
  580. if session.underlyingConn != underlyingConn {
  581. atomic.AddInt64(&session.metricUnderlyingConnCount, 1)
  582. session.underlyingConn = underlyingConn
  583. }
  584. // If a newer request has arrived while waiting, discard this one.
  585. // Do not delay processing the newest request.
  586. //
  587. // If the session expired and was deleted while this request was waiting,
  588. // discard this request. The session is no longer valid, and the final call
  589. // to session.cachedResponse.Reset may have already occured, so any further
  590. // session.cachedResponse access may deplete resources (fail to refill the pool).
  591. if atomic.LoadInt64(&session.requestCount) > requestNumber || session.deleted {
  592. common.TerminateHTTPConnection(responseWriter, request)
  593. return
  594. }
  595. // pumpReads causes a TunnelServer/SSH goroutine blocking on a Read to
  596. // read the request body as upstream traffic.
  597. // TODO: run pumpReads and pumpWrites concurrently?
  598. // pumpReads checksums the request payload and skips relaying it when
  599. // it matches the immediately previous request payload. This allows
  600. // clients to resend request payloads, when retrying due to connection
  601. // interruption, without knowing whether the server has received or
  602. // relayed the data.
  603. requestSize, err := session.clientConn.pumpReads(request.Body)
  604. if err != nil {
  605. if err != io.EOF {
  606. // Debug since errors such as "i/o timeout" occur during normal operation;
  607. // also, golang network error messages may contain client IP.
  608. log.WithTraceFields(LogFields{"error": err}).Debug("read request failed")
  609. }
  610. common.TerminateHTTPConnection(responseWriter, request)
  611. // Note: keep session open to allow client to retry
  612. return
  613. }
  614. // The extended turn around mechanism optimizes for downstream flows by
  615. // sending more data in the response as long as it's available. As a
  616. // heuristic, when the request size meets a threshold, optimize instead
  617. // of upstream flows by skipping the extended turn around.
  618. skipExtendedTurnAround := requestSize >= int64(server.skipExtendedTurnAroundThreshold)
  619. // Set cookie before writing the response.
  620. if session.meekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 && !session.sessionIDSent {
  621. // Replace the meek cookie with the session ID.
  622. // SetCookie for the the session ID cookie is only set once, to reduce overhead. This
  623. // session ID value replaces the original meek cookie value.
  624. http.SetCookie(responseWriter, &http.Cookie{Name: meekCookie.Name, Value: sessionID})
  625. session.sessionIDSent = true
  626. }
  627. // When streaming data into the response body, a copy is
  628. // retained in the cachedResponse buffer. This allows the
  629. // client to retry and request that the response be resent
  630. // when the HTTP connection is interrupted.
  631. //
  632. // If a Range header is present, the client is retrying,
  633. // possibly after having received a partial response. In
  634. // this case, use any cached response to attempt to resend
  635. // the response, starting from the resend position the client
  636. // indicates.
  637. //
  638. // When the resend position is not available -- because the
  639. // cachedResponse buffer could not hold it -- the client session
  640. // is closed, as there's no way to resume streaming the payload
  641. // uninterrupted.
  642. //
  643. // The client may retry before a cached response is prepared,
  644. // so a cached response is not always used when a Range header
  645. // is present.
  646. //
  647. // TODO: invalid Range header is ignored; should it be otherwise?
  648. position, isRetry := checkRangeHeader(request)
  649. if isRetry {
  650. atomic.AddInt64(&session.metricClientRetries, 1)
  651. }
  652. hasCompleteCachedResponse := session.cachedResponse.HasPosition(0)
  653. // The client is not expected to send position > 0 when there is
  654. // no cached response; let that case fall through to the next
  655. // HasPosition check which will fail and close the session.
  656. var responseSize int
  657. var responseError error
  658. if isRetry && (hasCompleteCachedResponse || position > 0) {
  659. if !session.cachedResponse.HasPosition(position) {
  660. greaterThanSwapInt64(&session.metricCachedResponseMissPosition, int64(position))
  661. server.handleError(responseWriter, request)
  662. session.delete(true)
  663. return
  664. }
  665. responseWriter.WriteHeader(http.StatusPartialContent)
  666. // TODO:
  667. // - enforce a max extended buffer count per client, for
  668. // fairness? Throttling may make this unnecessary.
  669. // - cachedResponse can now start releasing extended buffers,
  670. // as response bytes before "position" will never be requested
  671. // again?
  672. responseSize, responseError = session.cachedResponse.CopyFromPosition(position, responseWriter)
  673. greaterThanSwapInt64(&session.metricPeakCachedResponseHitSize, int64(responseSize))
  674. // The client may again fail to receive the payload and may again
  675. // retry, so not yet releasing cachedResponse buffers.
  676. } else {
  677. // _Now_ we release buffers holding data from the previous
  678. // response. And then immediately stream the new response into
  679. // newly acquired buffers.
  680. session.cachedResponse.Reset()
  681. // Note: this code depends on an implementation detail of
  682. // io.MultiWriter: a Write() to the MultiWriter writes first
  683. // to the cache, and then to the response writer. So if the
  684. // write to the response writer fails, the payload is cached.
  685. multiWriter := io.MultiWriter(session.cachedResponse, responseWriter)
  686. // The client expects 206, not 200, whenever it sets a Range header,
  687. // which it may do even when no cached response is prepared.
  688. if isRetry {
  689. responseWriter.WriteHeader(http.StatusPartialContent)
  690. }
  691. // pumpWrites causes a TunnelServer/SSH goroutine blocking on a Write to
  692. // write its downstream traffic through to the response body.
  693. responseSize, responseError = session.clientConn.pumpWrites(multiWriter, skipExtendedTurnAround)
  694. greaterThanSwapInt64(&session.metricPeakResponseSize, int64(responseSize))
  695. greaterThanSwapInt64(&session.metricPeakCachedResponseSize, int64(session.cachedResponse.Available()))
  696. }
  697. // responseError is the result of writing the body either from CopyFromPosition or pumpWrites
  698. if responseError != nil {
  699. if responseError != io.EOF {
  700. // Debug since errors such as "i/o timeout" occur during normal operation;
  701. // also, golang network error messages may contain client IP.
  702. log.WithTraceFields(LogFields{"error": responseError}).Debug("write response failed")
  703. }
  704. server.handleError(responseWriter, request)
  705. // Note: keep session open to allow client to retry
  706. return
  707. }
  708. }
  709. func (server *MeekServer) handleError(responseWriter http.ResponseWriter, request *http.Request) {
  710. // When fronted, keep the persistent connection open since it may be used
  711. // by many clients coming through the same edge. For performance reasons,
  712. // an error, including invalid input, from one client shouldn't close the
  713. // persistent connection used by other clients.
  714. if server.isFronted {
  715. http.NotFound(responseWriter, request)
  716. return
  717. }
  718. common.TerminateHTTPConnection(responseWriter, request)
  719. }
  720. func checkRangeHeader(request *http.Request) (int, bool) {
  721. rangeHeader := request.Header.Get("Range")
  722. if rangeHeader == "" {
  723. return 0, false
  724. }
  725. prefix := "bytes="
  726. suffix := "-"
  727. if !strings.HasPrefix(rangeHeader, prefix) ||
  728. !strings.HasSuffix(rangeHeader, suffix) {
  729. return 0, false
  730. }
  731. rangeHeader = strings.TrimPrefix(rangeHeader, prefix)
  732. rangeHeader = strings.TrimSuffix(rangeHeader, suffix)
  733. position, err := strconv.Atoi(rangeHeader)
  734. if err != nil {
  735. return 0, false
  736. }
  737. return position, true
  738. }
  739. // getSessionOrEndpoint checks if the cookie corresponds to an existing tunnel
  740. // relay session ID. If no session is found, the cookie must be an obfuscated
  741. // meek cookie. A new session is created when the meek cookie indicates relay
  742. // mode; or the endpoint is returned when the meek cookie indicates endpoint
  743. // mode.
  744. //
  745. // For performance reasons, in-proxy broker requests are allowed to omit the
  746. // meek cookie and pass in nil for meekCookie; getSessionOrEndpoint still
  747. // performs rate limiting and header handling for the in-proxy broker case.
  748. func (server *MeekServer) getSessionOrEndpoint(
  749. request *http.Request,
  750. meekCookie *http.Cookie) (string, *meekSession, net.Conn, string, string, *GeoIPData, error) {
  751. underlyingConn := request.Context().Value(meekNetConnContextKey).(net.Conn)
  752. // Check for an existing meek tunnel session.
  753. if meekCookie != nil {
  754. server.sessionsLock.RLock()
  755. existingSessionID := meekCookie.Value
  756. session, ok := server.sessions[existingSessionID]
  757. server.sessionsLock.RUnlock()
  758. if ok {
  759. // TODO: can multiple http client connections using same session cookie
  760. // cause race conditions on session struct?
  761. session.touch()
  762. return existingSessionID, session, underlyingConn, "", "", nil, nil
  763. }
  764. }
  765. // TODO: rename clientIP to peerIP to reflect the new terminology used in
  766. // psiphon/server code where the immediate peer may be an in-proxy proxy,
  767. // not the client.
  768. // Determine the client or peer remote address, which is used for
  769. // geolocation stats, rate limiting, anti-probing, discovery, and tactics
  770. // selection logic.
  771. //
  772. // When an intermediate proxy or CDN is in use, we may be
  773. // able to determine the original client address by inspecting HTTP
  774. // headers such as X-Forwarded-For.
  775. //
  776. // We trust only headers provided by CDNs. Fronted Psiphon server hosts
  777. // should be configured to accept tunnel connections only from CDN edges.
  778. // When the CDN passes along a chain of IPs, as in X-Forwarded-For, we
  779. // trust only the right-most IP, which is provided by the CDN.
  780. clientIP, _, err := net.SplitHostPort(request.RemoteAddr)
  781. if err != nil {
  782. return "", nil, nil, "", "", nil, errors.Trace(err)
  783. }
  784. if net.ParseIP(clientIP) == nil {
  785. return "", nil, nil, "", "", nil, errors.TraceNew("invalid IP address")
  786. }
  787. if server.isFronted && len(server.support.Config.MeekProxyForwardedForHeaders) > 0 {
  788. // When there are multiple header names in MeekProxyForwardedForHeaders,
  789. // the first valid match is preferred. MeekProxyForwardedForHeaders should be
  790. // configured to use header names that are always provided by the CDN(s) and
  791. // not header names that may be passed through from clients.
  792. for _, header := range server.support.Config.MeekProxyForwardedForHeaders {
  793. // In the case where there are multiple headers,
  794. // request.Header.Get returns the first header, but we want the
  795. // last header; so use request.Header.Values and select the last
  796. // value. As per RFC 2616 section 4.2, a proxy must not change
  797. // the order of field values, which implies that it should append
  798. // values to the last header.
  799. values := request.Header.Values(header)
  800. if len(values) > 0 {
  801. value := values[len(values)-1]
  802. // Some headers, such as X-Forwarded-For, are a comma-separated
  803. // list of IPs (each proxy in a chain). Select the last IP.
  804. IPs := strings.Split(value, ",")
  805. IP := IPs[len(IPs)-1]
  806. // Remove optional whitespace surrounding the commas.
  807. IP = strings.TrimSpace(IP)
  808. if net.ParseIP(IP) != nil {
  809. clientIP = IP
  810. break
  811. }
  812. }
  813. }
  814. }
  815. geoIPData := server.support.GeoIPService.Lookup(clientIP)
  816. // Check for a steering IP header, which contains an alternate dial IP to
  817. // be returned to the client via the secure API handshake response.
  818. // Steering may be used to load balance CDN traffic.
  819. //
  820. // The steering IP header is added by a CDN or CDN service process. To
  821. // prevent steering IP spoofing, the service process must filter out any
  822. // steering IP headers injected into ingress requests.
  823. //
  824. // Steering IP headers must appear in the first request of a meek session
  825. // in order to be recorded here and relayed to the client.
  826. var steeringIP string
  827. if server.isFronted && server.support.Config.EnableSteeringIPs {
  828. steeringIP = request.Header.Get("X-Psiphon-Steering-Ip")
  829. if steeringIP != "" {
  830. IP := net.ParseIP(steeringIP)
  831. if IP == nil || common.IsBogon(IP) {
  832. steeringIP = ""
  833. log.WithTraceFields(LogFields{"steeringIP": steeringIP}).Warning("invalid steering IP")
  834. }
  835. }
  836. }
  837. // The session is new (or expired). Treat the cookie value as a new meek
  838. // cookie, extract the payload, and create a new session.
  839. // Limitation: when the cookie is a session ID for an expired session, we
  840. // still attempt to treat it as a meek cookie. As it stands, that yields
  841. // either base64 decoding errors (RawStdEncoding vs. StdEncoding) or
  842. // length errors. We could log cleaner errors ("session is expired") by
  843. // checking that the cookie is a well-formed (base64.RawStdEncoding) value
  844. // between MEEK_MIN_SESSION_ID_LENGTH and MEEK_MAX_SESSION_ID_LENGTH
  845. // bytes -- assuming that MEEK_MAX_SESSION_ID_LENGTH is too short to be a
  846. // valid meek cookie.
  847. var payloadJSON []byte
  848. if server.normalizer != nil {
  849. // Limitation: RunInproxyBroker mode with no meek cookies is not
  850. // compatible with the HTTP normalizer.
  851. // NOTE: operates on the assumption that the normalizer is not wrapped
  852. // with a further conn.
  853. underlyingConn := request.Context().Value(meekNetConnContextKey).(net.Conn)
  854. normalizedConn := underlyingConn.(*transforms.HTTPNormalizer)
  855. payloadJSON = normalizedConn.ValidateMeekCookieResult
  856. } else {
  857. if meekCookie != nil {
  858. payloadJSON, err = server.getMeekCookiePayload(clientIP, meekCookie.Value)
  859. if err != nil {
  860. return "", nil, nil, "", "", nil, errors.Trace(err)
  861. }
  862. }
  863. }
  864. // Note: this meek server ignores legacy values PsiphonClientSessionId
  865. // and PsiphonServerAddress.
  866. var clientSessionData protocol.MeekCookieData
  867. if meekCookie != nil {
  868. err = json.Unmarshal(payloadJSON, &clientSessionData)
  869. if err != nil {
  870. return "", nil, nil, "", "", nil, errors.Trace(err)
  871. }
  872. } else {
  873. // Assume the in-proxy broker endpoint when there's no meek cookie.
  874. clientSessionData.EndPoint = inproxy.BrokerEndPointName
  875. }
  876. // Any rate limit is enforced after the meek cookie is validated, so a prober
  877. // without the obfuscation secret will be unable to fingerprint the server
  878. // based on response time combined with the rate limit configuration. The
  879. // rate limit is primarily intended to limit memory resource consumption and
  880. // not the overhead incurred by cookie validation.
  881. if server.rateLimit(clientIP, geoIPData, server.listenerTunnelProtocol) {
  882. return "", nil, nil, "", "", nil, errors.TraceNew("rate limit exceeded")
  883. }
  884. // Handle endpoints before enforcing CheckEstablishTunnels.
  885. // Currently, endpoints are tactics requests, and we allow these to be
  886. // handled by servers which would otherwise reject new tunnels.
  887. if clientSessionData.EndPoint != "" {
  888. return "", nil, nil, clientSessionData.EndPoint, clientIP, &geoIPData, nil
  889. }
  890. // After this point, for the meek tunnel new session case, a meek cookie
  891. // is required and meekCookie must not be nil.
  892. if meekCookie == nil {
  893. return "", nil, nil, "", "", nil, errors.TraceNew("missing meek cookie")
  894. }
  895. // Don't create new sessions when not establishing. A subsequent SSH handshake
  896. // will not succeed, so creating a meek session just wastes resources.
  897. if server.support.TunnelServer != nil &&
  898. !server.support.TunnelServer.CheckEstablishTunnels() {
  899. return "", nil, nil, "", "", nil, errors.TraceNew("not establishing tunnels")
  900. }
  901. // Disconnect immediately if the tactics for the client restricts usage of
  902. // the fronting provider ID. The probability may be used to influence
  903. // usage of a given fronting provider; but when only that provider works
  904. // for a given client, and the probability is less than 1.0, the client
  905. // can retry until it gets a successful coin flip.
  906. //
  907. // Clients will also skip candidates with restricted fronting provider IDs.
  908. // The client-side probability, RestrictFrontingProviderIDsClientProbability,
  909. // is applied independently of the server-side coin flip here.
  910. //
  911. // At this stage, GeoIP tactics filters are active, but handshake API
  912. // parameters are not.
  913. //
  914. // See the comment in server.LoadConfig regarding fronting provider ID
  915. // limitations.
  916. if protocol.TunnelProtocolUsesFrontedMeek(server.listenerTunnelProtocol) &&
  917. server.support.ServerTacticsParametersCache != nil {
  918. p, err := server.support.ServerTacticsParametersCache.Get(geoIPData)
  919. if err != nil {
  920. return "", nil, nil, "", "", nil, errors.Trace(err)
  921. }
  922. if !p.IsNil() &&
  923. common.Contains(
  924. p.Strings(parameters.RestrictFrontingProviderIDs),
  925. server.support.Config.GetFrontingProviderID()) {
  926. if p.WeightedCoinFlip(
  927. parameters.RestrictFrontingProviderIDsServerProbability) {
  928. return "", nil, nil, "", "", nil, errors.TraceNew("restricted fronting provider")
  929. }
  930. }
  931. }
  932. // The tunnel protocol name is used for stats and traffic rules. In many
  933. // cases, its value is unambiguously determined by the listener port. In
  934. // certain cases, such as multiple fronted protocols with a single
  935. // backend listener, the client's reported tunnel protocol value is used.
  936. // The caller must validate clientTunnelProtocol with
  937. // protocol.IsValidClientTunnelProtocol.
  938. var clientTunnelProtocol string
  939. if clientSessionData.ClientTunnelProtocol != "" {
  940. if !protocol.IsValidClientTunnelProtocol(
  941. clientSessionData.ClientTunnelProtocol,
  942. server.listenerTunnelProtocol,
  943. server.support.Config.GetRunningProtocols()) {
  944. return "", nil, nil, "", "", nil, errors.Tracef(
  945. "invalid client tunnel protocol: %s", clientSessionData.ClientTunnelProtocol)
  946. }
  947. clientTunnelProtocol = clientSessionData.ClientTunnelProtocol
  948. }
  949. // Create a new session
  950. bufferLength := MEEK_DEFAULT_RESPONSE_BUFFER_LENGTH
  951. if server.support.Config.MeekCachedResponseBufferSize != 0 {
  952. bufferLength = server.support.Config.MeekCachedResponseBufferSize
  953. }
  954. cachedResponse := NewCachedResponse(bufferLength, server.bufferPool)
  955. // The cookie name, Content-Type, and HTTP version of the first request in
  956. // the session are recorded for stats. It's possible, but not expected,
  957. // that later requests will have different values.
  958. session := &meekSession{
  959. meekProtocolVersion: clientSessionData.MeekProtocolVersion,
  960. sessionIDSent: false,
  961. cachedResponse: cachedResponse,
  962. cookieName: meekCookie.Name,
  963. contentType: request.Header.Get("Content-Type"),
  964. httpVersion: request.Proto,
  965. }
  966. session.touch()
  967. // Create a new meek conn that will relay the payload
  968. // between meek request/responses and the tunnel server client
  969. // handler. The client IP is also used to initialize the
  970. // meek conn with a useful value to return when the tunnel
  971. // server calls conn.RemoteAddr() to get the client's IP address.
  972. // Assumes clientIP is a valid IP address; the port value is a stub
  973. // and is expected to be ignored.
  974. clientConn := newMeekConn(
  975. server,
  976. session,
  977. underlyingConn,
  978. &net.TCPAddr{
  979. IP: net.ParseIP(clientIP),
  980. Port: 0,
  981. },
  982. clientSessionData.MeekProtocolVersion)
  983. session.clientConn = clientConn
  984. // Note: MEEK_PROTOCOL_VERSION_1 doesn't support changing the
  985. // meek cookie to a session ID; v1 clients always send the
  986. // original meek cookie value with each request. The issue with
  987. // v1 is that clients which wake after a device sleep will attempt
  988. // to resume a meek session and the server can't differentiate
  989. // between resuming a session and creating a new session. This
  990. // causes the v1 client connection to hang/timeout.
  991. sessionID := meekCookie.Value
  992. if clientSessionData.MeekProtocolVersion >= MEEK_PROTOCOL_VERSION_2 {
  993. sessionID, err = makeMeekSessionID()
  994. if err != nil {
  995. return "", nil, nil, "", "", nil, errors.Trace(err)
  996. }
  997. }
  998. server.sessionsLock.Lock()
  999. server.sessions[sessionID] = session
  1000. server.sessionsLock.Unlock()
  1001. var additionalData *additionalTransportData
  1002. if clientTunnelProtocol != "" || steeringIP != "" {
  1003. additionalData = &additionalTransportData{
  1004. overrideTunnelProtocol: clientTunnelProtocol,
  1005. steeringIP: steeringIP,
  1006. }
  1007. }
  1008. // Note: from the tunnel server's perspective, this client connection
  1009. // will close when session.delete calls Close() on the meekConn.
  1010. server.clientHandler(session.clientConn, additionalData)
  1011. return sessionID, session, underlyingConn, "", "", nil, nil
  1012. }
  1013. func (server *MeekServer) rateLimit(
  1014. clientIP string, geoIPData GeoIPData, tunnelProtocol string) bool {
  1015. historySize,
  1016. thresholdSeconds,
  1017. tunnelProtocols,
  1018. regions,
  1019. ISPs,
  1020. ASNs,
  1021. cities,
  1022. GCTriggerCount, _, _ :=
  1023. server.support.TrafficRulesSet.GetMeekRateLimiterConfig()
  1024. if historySize == 0 {
  1025. return false
  1026. }
  1027. if len(tunnelProtocols) > 0 {
  1028. if !common.Contains(tunnelProtocols, tunnelProtocol) {
  1029. return false
  1030. }
  1031. }
  1032. if len(regions) > 0 || len(ISPs) > 0 || len(ASNs) > 0 || len(cities) > 0 {
  1033. if len(regions) > 0 {
  1034. if !common.Contains(regions, geoIPData.Country) {
  1035. return false
  1036. }
  1037. }
  1038. if len(ISPs) > 0 {
  1039. if !common.Contains(ISPs, geoIPData.ISP) {
  1040. return false
  1041. }
  1042. }
  1043. if len(ASNs) > 0 {
  1044. if !common.Contains(ASNs, geoIPData.ASN) {
  1045. return false
  1046. }
  1047. }
  1048. if len(cities) > 0 {
  1049. if !common.Contains(cities, geoIPData.City) {
  1050. return false
  1051. }
  1052. }
  1053. }
  1054. // With IPv6, individual users or sites are users commonly allocated a /64
  1055. // or /56, so rate limit by /56.
  1056. rateLimitIP := clientIP
  1057. IP := net.ParseIP(clientIP)
  1058. if IP != nil && IP.To4() == nil {
  1059. rateLimitIP = IP.Mask(net.CIDRMask(56, 128)).String()
  1060. }
  1061. // go-cache-lru is safe for concurrent access, but lacks an atomic
  1062. // compare-and-set type operations to check if an entry exists before
  1063. // adding a new one. This mutex ensures the Get and Add are atomic
  1064. // (as well as synchronizing access to rateLimitCount).
  1065. server.rateLimitLock.Lock()
  1066. var rateLimiter *ratelimit.Bucket
  1067. entry, ok := server.rateLimitHistory.Get(rateLimitIP)
  1068. if ok {
  1069. rateLimiter = entry.(*ratelimit.Bucket)
  1070. } else {
  1071. rateLimiter = ratelimit.NewBucketWithQuantum(
  1072. time.Duration(thresholdSeconds)*time.Second,
  1073. int64(historySize),
  1074. int64(historySize))
  1075. server.rateLimitHistory.Set(
  1076. rateLimitIP,
  1077. rateLimiter,
  1078. time.Duration(thresholdSeconds)*time.Second)
  1079. }
  1080. limit := rateLimiter.TakeAvailable(1) < 1
  1081. triggerGC := false
  1082. if limit {
  1083. server.rateLimitCount += 1
  1084. if server.rateLimitCount >= GCTriggerCount {
  1085. triggerGC = true
  1086. server.rateLimitCount = 0
  1087. }
  1088. }
  1089. server.rateLimitLock.Unlock()
  1090. if triggerGC {
  1091. select {
  1092. case server.rateLimitSignalGC <- struct{}{}:
  1093. default:
  1094. }
  1095. }
  1096. return limit
  1097. }
  1098. func (server *MeekServer) rateLimitWorker() {
  1099. for {
  1100. select {
  1101. case <-server.rateLimitSignalGC:
  1102. runtime.GC()
  1103. case <-server.stopBroadcast:
  1104. return
  1105. }
  1106. }
  1107. }
  1108. func (server *MeekServer) deleteSession(sessionID string) {
  1109. // Don't obtain the server.sessionsLock write lock until modifying
  1110. // server.sessions, as the session.delete can block for up to
  1111. // MEEK_HTTP_CLIENT_IO_TIMEOUT. Allow new sessions to be added
  1112. // concurrently.
  1113. //
  1114. // Since a lock isn't held for the duration, concurrent calls to
  1115. // deleteSession with the same sessionID could happen; this is
  1116. // not expected since only the reaper goroutine calls deleteExpiredSessions
  1117. // (and in any case concurrent execution of the ok block is not an issue).
  1118. server.sessionsLock.RLock()
  1119. session, ok := server.sessions[sessionID]
  1120. server.sessionsLock.RUnlock()
  1121. if ok {
  1122. session.delete(false)
  1123. server.sessionsLock.Lock()
  1124. delete(server.sessions, sessionID)
  1125. server.sessionsLock.Unlock()
  1126. }
  1127. }
  1128. func (server *MeekServer) deleteExpiredSessions() {
  1129. // A deleteSession call may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  1130. // so grab a snapshot list of expired sessions and do not hold a lock for
  1131. // the duration of deleteExpiredSessions. This allows new sessions to be
  1132. // added concurrently.
  1133. //
  1134. // New sessions added after the snapshot is taken will be checked for
  1135. // expiry on subsequent periodic calls to deleteExpiredSessions.
  1136. //
  1137. // To avoid long delays in releasing resources, individual deletes are
  1138. // performed concurrently.
  1139. server.sessionsLock.Lock()
  1140. expiredSessionIDs := make([]string, 0)
  1141. for sessionID, session := range server.sessions {
  1142. if session.expired() {
  1143. expiredSessionIDs = append(expiredSessionIDs, sessionID)
  1144. }
  1145. }
  1146. server.sessionsLock.Unlock()
  1147. start := time.Now()
  1148. deleteWaitGroup := new(sync.WaitGroup)
  1149. for _, sessionID := range expiredSessionIDs {
  1150. deleteWaitGroup.Add(1)
  1151. go func(sessionID string) {
  1152. defer deleteWaitGroup.Done()
  1153. server.deleteSession(sessionID)
  1154. }(sessionID)
  1155. }
  1156. deleteWaitGroup.Wait()
  1157. log.WithTraceFields(
  1158. LogFields{"elapsed time": time.Since(start)}).Debug("deleted expired sessions")
  1159. }
  1160. // httpConnStateCallback tracks open persistent HTTP/HTTPS connections to the
  1161. // meek server.
  1162. func (server *MeekServer) httpConnStateCallback(conn net.Conn, connState http.ConnState) {
  1163. switch connState {
  1164. case http.StateNew:
  1165. server.openConns.Add(conn)
  1166. case http.StateHijacked, http.StateClosed:
  1167. server.openConns.Remove(conn)
  1168. }
  1169. }
  1170. // getMeekCookiePayload extracts the payload from a meek cookie. The cookie
  1171. // payload is base64 encoded, obfuscated, and NaCl encrypted.
  1172. func (server *MeekServer) getMeekCookiePayload(
  1173. clientIP string, cookieValue string) ([]byte, error) {
  1174. decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
  1175. if err != nil {
  1176. return nil, errors.Trace(err)
  1177. }
  1178. // The data consists of an obfuscated seed message prepended
  1179. // to the obfuscated, encrypted payload. The server obfuscator
  1180. // will read the seed message, leaving the remaining encrypted
  1181. // data in the reader.
  1182. reader := bytes.NewReader(decodedValue[:])
  1183. obfuscator, err := obfuscator.NewServerObfuscator(
  1184. &obfuscator.ObfuscatorConfig{
  1185. Keyword: server.support.Config.MeekObfuscatedKey,
  1186. SeedHistory: server.obfuscatorSeedHistory,
  1187. IrregularLogger: func(clientIP string, err error, logFields common.LogFields) {
  1188. logIrregularTunnel(
  1189. server.support,
  1190. server.listenerTunnelProtocol,
  1191. server.listenerPort,
  1192. clientIP,
  1193. errors.Trace(err),
  1194. LogFields(logFields))
  1195. },
  1196. },
  1197. clientIP,
  1198. reader)
  1199. if err != nil {
  1200. return nil, errors.Trace(err)
  1201. }
  1202. offset, err := reader.Seek(0, 1)
  1203. if err != nil {
  1204. return nil, errors.Trace(err)
  1205. }
  1206. encryptedPayload := decodedValue[offset:]
  1207. obfuscator.ObfuscateClientToServer(encryptedPayload)
  1208. var nonce [24]byte
  1209. var privateKey, ephemeralPublicKey [32]byte
  1210. decodedPrivateKey, err := base64.StdEncoding.DecodeString(
  1211. server.support.Config.MeekCookieEncryptionPrivateKey)
  1212. if err != nil {
  1213. return nil, errors.Trace(err)
  1214. }
  1215. copy(privateKey[:], decodedPrivateKey)
  1216. if len(encryptedPayload) < 32 {
  1217. return nil, errors.TraceNew("unexpected encrypted payload size")
  1218. }
  1219. copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
  1220. payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
  1221. if !ok {
  1222. return nil, errors.TraceNew("open box failed")
  1223. }
  1224. return payload, nil
  1225. }
  1226. func (server *MeekServer) getWebServerCertificate() ([]byte, []byte, error) {
  1227. var certificate, privateKey string
  1228. if server.support.Config.MeekServerCertificate != "" {
  1229. certificate = server.support.Config.MeekServerCertificate
  1230. privateKey = server.support.Config.MeekServerPrivateKey
  1231. } else {
  1232. var err error
  1233. certificate, privateKey, _, err = common.GenerateWebServerCertificate(values.GetHostName())
  1234. if err != nil {
  1235. return nil, nil, errors.Trace(err)
  1236. }
  1237. }
  1238. return []byte(certificate), []byte(privateKey), nil
  1239. }
  1240. // makeFrontedMeekTLSConfig creates a TLS config for a fronted meek HTTPS
  1241. // listener.
  1242. func (server *MeekServer) makeFrontedMeekTLSConfig() (*tls.Config, error) {
  1243. certificate, privateKey, err := server.getWebServerCertificate()
  1244. if err != nil {
  1245. return nil, errors.Trace(err)
  1246. }
  1247. tlsCertificate, err := tls.X509KeyPair(
  1248. []byte(certificate), []byte(privateKey))
  1249. if err != nil {
  1250. return nil, errors.Trace(err)
  1251. }
  1252. // Vary the minimum version to frustrate scanning/fingerprinting of unfronted servers.
  1253. // Limitation: like the certificate, this value changes on restart.
  1254. minVersionCandidates := []uint16{tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12}
  1255. minVersion := minVersionCandidates[prng.Intn(len(minVersionCandidates))]
  1256. // This is a reordering of the supported CipherSuites in golang 1.6[*]. Non-ephemeral key
  1257. // CipherSuites greatly reduce server load, and we try to select these since the meek
  1258. // protocol is providing obfuscation, not privacy/integrity (this is provided by the
  1259. // tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
  1260. // by ephemeral key CipherSuites.
  1261. // https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
  1262. //
  1263. // This optimization is applied only when there's a CDN in front of the meek server; in
  1264. // unfronted cases we prefer a more natural TLS handshake.
  1265. //
  1266. // [*] the list has since been updated, removing CipherSuites using RC4 and 3DES.
  1267. cipherSuites := []uint16{
  1268. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  1269. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  1270. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  1271. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  1272. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1273. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1274. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1275. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1276. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  1277. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  1278. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  1279. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  1280. }
  1281. config := &tls.Config{
  1282. Certificates: []tls.Certificate{tlsCertificate},
  1283. // Offer and prefer "h2" for HTTP/2 support.
  1284. NextProtos: []string{"h2", "http/1.1"},
  1285. MinVersion: minVersion,
  1286. CipherSuites: cipherSuites,
  1287. }
  1288. return config, nil
  1289. }
  1290. // makeDirectMeekTLSConfig creates a TLS config for a direct meek HTTPS
  1291. // listener.
  1292. func (server *MeekServer) makeDirectMeekTLSConfig(
  1293. useObfuscatedSessionTickets bool) (*psiphon_tls.Config, error) {
  1294. certificate, privateKey, err := server.getWebServerCertificate()
  1295. if err != nil {
  1296. return nil, errors.Trace(err)
  1297. }
  1298. tlsCertificate, err := psiphon_tls.X509KeyPair(
  1299. []byte(certificate), []byte(privateKey))
  1300. if err != nil {
  1301. return nil, errors.Trace(err)
  1302. }
  1303. // Vary the minimum version to frustrate scanning/fingerprinting of unfronted servers.
  1304. // Limitation: like the certificate, this value changes on restart.
  1305. minVersionCandidates := []uint16{tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12}
  1306. minVersion := minVersionCandidates[prng.Intn(len(minVersionCandidates))]
  1307. config := &psiphon_tls.Config{
  1308. Certificates: []psiphon_tls.Certificate{tlsCertificate},
  1309. // Omit "h2", so HTTP/2 is not negotiated. Note that the
  1310. // negotiated-ALPN extension in the ServerHello is plaintext, even in
  1311. // TLS 1.3.
  1312. NextProtos: []string{"http/1.1"},
  1313. MinVersion: minVersion,
  1314. }
  1315. if useObfuscatedSessionTickets {
  1316. // See obfuscated session ticket overview
  1317. // in NewObfuscatedClientSessionState.
  1318. config.UseObfuscatedSessionTickets = true
  1319. var obfuscatedSessionTicketKey [32]byte
  1320. key, err := hex.DecodeString(server.support.Config.MeekObfuscatedKey)
  1321. if err == nil && len(key) != 32 {
  1322. err = std_errors.New("invalid obfuscated session key length")
  1323. }
  1324. if err != nil {
  1325. return nil, errors.Trace(err)
  1326. }
  1327. copy(obfuscatedSessionTicketKey[:], key)
  1328. var standardSessionTicketKey [32]byte
  1329. _, err = rand.Read(standardSessionTicketKey[:])
  1330. if err != nil {
  1331. return nil, errors.Trace(err)
  1332. }
  1333. // Note: SessionTicketKey needs to be set, or else, it appears,
  1334. // tris.Config.serverInit() will clobber the value set by
  1335. // SetSessionTicketKeys.
  1336. config.SessionTicketKey = obfuscatedSessionTicketKey
  1337. config.SetSessionTicketKeys([][32]byte{
  1338. standardSessionTicketKey,
  1339. obfuscatedSessionTicketKey})
  1340. }
  1341. // When configured, initialize passthrough mode, an anti-probing defense.
  1342. // Clients must prove knowledge of the obfuscated key via a message sent in
  1343. // the TLS ClientHello random field.
  1344. //
  1345. // When clients fail to provide a valid message, the client connection is
  1346. // relayed to the designated passthrough address, typically another web site.
  1347. // The entire flow is relayed, including the original ClientHello, so the
  1348. // client will perform a TLS handshake with the passthrough target.
  1349. //
  1350. // Irregular events are logged for invalid client activity.
  1351. if server.passthroughAddress != "" {
  1352. config.PassthroughAddress = server.passthroughAddress
  1353. config.PassthroughVerifyMessage = func(
  1354. message []byte) bool {
  1355. return obfuscator.VerifyTLSPassthroughMessage(
  1356. !server.support.Config.LegacyPassthrough,
  1357. server.support.Config.MeekObfuscatedKey,
  1358. message)
  1359. }
  1360. config.PassthroughLogInvalidMessage = func(
  1361. clientIP string) {
  1362. logIrregularTunnel(
  1363. server.support,
  1364. server.listenerTunnelProtocol,
  1365. server.listenerPort,
  1366. clientIP,
  1367. errors.TraceNew("invalid passthrough message"),
  1368. nil)
  1369. }
  1370. config.PassthroughHistoryAddNew = func(
  1371. clientIP string,
  1372. clientRandom []byte) bool {
  1373. // Use a custom, shorter TTL based on the validity period of the
  1374. // passthrough message.
  1375. TTL := obfuscator.TLS_PASSTHROUGH_HISTORY_TTL
  1376. if server.support.Config.LegacyPassthrough {
  1377. TTL = obfuscator.HISTORY_SEED_TTL
  1378. }
  1379. // strictMode is true as, unlike with meek cookies, legitimate meek clients
  1380. // never retry TLS connections using a previous random value.
  1381. ok, logFields := server.obfuscatorSeedHistory.AddNewWithTTL(
  1382. true,
  1383. clientIP,
  1384. "client-random",
  1385. clientRandom,
  1386. TTL)
  1387. if logFields != nil {
  1388. logIrregularTunnel(
  1389. server.support,
  1390. server.listenerTunnelProtocol,
  1391. server.listenerPort,
  1392. clientIP,
  1393. errors.TraceNew("duplicate passthrough message"),
  1394. LogFields(*logFields))
  1395. }
  1396. return ok
  1397. }
  1398. }
  1399. return config, nil
  1400. }
  1401. // makeMeekHTTPNormalizerListener returns the meek server listener wrapped in
  1402. // an HTTP normalizer.
  1403. func (server *MeekServer) makeMeekHTTPNormalizerListener() *transforms.HTTPNormalizerListener {
  1404. normalizer := transforms.WrapListenerWithHTTPNormalizer(server.listener)
  1405. normalizer.ProhibitedHeaders = server.support.Config.MeekProhibitedHeaders
  1406. normalizer.MaxReqLineAndHeadersSize = 8192 // max number of header bytes common web servers will read before returning an error
  1407. if server.passthroughAddress != "" {
  1408. normalizer.PassthroughAddress = server.passthroughAddress
  1409. normalizer.PassthroughDialer = net.Dial
  1410. }
  1411. normalizer.PassthroughLogPassthrough = func(
  1412. clientIP string, tunnelError error, logFields map[string]interface{}) {
  1413. logIrregularTunnel(
  1414. server.support,
  1415. server.listenerTunnelProtocol,
  1416. server.listenerPort,
  1417. clientIP,
  1418. errors.Trace(tunnelError),
  1419. logFields)
  1420. }
  1421. // ValidateMeekCookie is invoked by the normalizer with the value of the
  1422. // cookie header (if present), before ServeHTTP gets the request and calls
  1423. // getSessionOrEndpoint; and then any valid meek cookie payload, or meek
  1424. // session ID, extracted in this callback is stored to be fetched by
  1425. // getSessionOrEndpoint.
  1426. // Note: if there are multiple cookie headers, even though prohibited by
  1427. // rfc6265, then ValidateMeekCookie will only be invoked once with the
  1428. // first one received.
  1429. normalizer.ValidateMeekCookie = func(clientIP string, rawCookies []byte) ([]byte, error) {
  1430. // Parse cookie.
  1431. if len(rawCookies) == 0 {
  1432. return nil, errors.TraceNew("no cookies")
  1433. }
  1434. // TODO/perf: readCookies in net/http is not exported, use a local
  1435. // implementation which does not require allocating an http.header
  1436. // each time.
  1437. request := http.Request{
  1438. Header: http.Header{
  1439. "Cookie": []string{string(rawCookies)},
  1440. },
  1441. }
  1442. cookies := request.Cookies()
  1443. if len(rawCookies) == 0 {
  1444. return nil, errors.Tracef("invalid cookies: %s", string(rawCookies))
  1445. }
  1446. // Use value of the first cookie.
  1447. meekCookieValue := cookies[0].Value
  1448. // Check for an existing session.
  1449. server.sessionsLock.RLock()
  1450. existingSessionID := meekCookieValue
  1451. _, ok := server.sessions[existingSessionID]
  1452. server.sessionsLock.RUnlock()
  1453. if ok {
  1454. // The cookie is a session ID for an active (not expired) session.
  1455. // Return it and then it will be stored and later fetched by
  1456. // getSessionOrEndpoint where it will be mapped to the existing
  1457. // session.
  1458. // Note: it's possible for the session to expire between this check
  1459. // and when getSessionOrEndpoint looks up the session.
  1460. return rawCookies, nil
  1461. }
  1462. // The session is new (or expired). Treat the cookie value as a new
  1463. // meek cookie, extract the payload, and return it; and then it will be
  1464. // stored and later fetched by getSessionOrEndpoint.
  1465. payloadJSON, err := server.getMeekCookiePayload(clientIP, meekCookieValue)
  1466. if err != nil {
  1467. return nil, errors.Trace(err)
  1468. }
  1469. return payloadJSON, nil
  1470. }
  1471. return normalizer
  1472. }
  1473. func (server *MeekServer) inproxyReloadTactics() error {
  1474. // Assumes no GeoIP targeting for InproxyAllCommonCompartmentIDs and other
  1475. // general broker tactics.
  1476. p, err := server.support.ServerTacticsParametersCache.Get(NewGeoIPData())
  1477. if err != nil {
  1478. return errors.Trace(err)
  1479. }
  1480. if p.IsNil() {
  1481. return nil
  1482. }
  1483. commonCompartmentIDs, err := inproxy.IDsFromStrings(
  1484. p.Strings(parameters.InproxyAllCommonCompartmentIDs))
  1485. if err != nil {
  1486. return errors.Trace(err)
  1487. }
  1488. server.inproxyBroker.SetCommonCompartmentIDs(commonCompartmentIDs)
  1489. server.inproxyBroker.SetTimeouts(
  1490. p.Duration(parameters.InproxyProxyAnnounceRequestTimeout),
  1491. p.Duration(parameters.InproxyClientOfferRequestTimeout),
  1492. p.Duration(parameters.InproxyBrokerPendingServerRequestsTTL))
  1493. nonlimitedProxyIDs, err := inproxy.IDsFromStrings(
  1494. p.Strings(parameters.InproxyBrokerMatcherAnnouncementNonlimitedProxyIDs))
  1495. if err != nil {
  1496. return errors.Trace(err)
  1497. }
  1498. server.inproxyBroker.SetLimits(
  1499. p.Int(parameters.InproxyBrokerMatcherAnnouncementLimitEntryCount),
  1500. p.Int(parameters.InproxyBrokerMatcherAnnouncementRateLimitQuantity),
  1501. p.Duration(parameters.InproxyBrokerMatcherAnnouncementRateLimitInterval),
  1502. nonlimitedProxyIDs,
  1503. p.Int(parameters.InproxyBrokerMatcherOfferLimitEntryCount),
  1504. p.Int(parameters.InproxyBrokerMatcherOfferRateLimitQuantity),
  1505. p.Duration(parameters.InproxyBrokerMatcherOfferRateLimitInterval),
  1506. p.Int(parameters.InproxyMaxCompartmentIDListLength))
  1507. return nil
  1508. }
  1509. func (server *MeekServer) lookupAllowTactic(geoIPData common.GeoIPData, parameterName string) bool {
  1510. // Fallback to not-allow on failure or nil tactics.
  1511. p, err := server.support.ServerTacticsParametersCache.Get(GeoIPData(geoIPData))
  1512. if err != nil {
  1513. log.WithTraceFields(LogFields{"error": err}).Warning("ServerTacticsParametersCache.Get failed")
  1514. return false
  1515. }
  1516. if p.IsNil() {
  1517. return false
  1518. }
  1519. return p.Bool(parameterName)
  1520. }
  1521. func (server *MeekServer) inproxyBrokerAllowProxy(proxyGeoIPData common.GeoIPData) bool {
  1522. return server.lookupAllowTactic(proxyGeoIPData, parameters.InproxyAllowProxy)
  1523. }
  1524. func (server *MeekServer) inproxyBrokerAllowClient(clientGeoIPData common.GeoIPData) bool {
  1525. return server.lookupAllowTactic(clientGeoIPData, parameters.InproxyAllowClient)
  1526. }
  1527. func (server *MeekServer) inproxyBrokerAllowDomainFrontedDestinations(clientGeoIPData common.GeoIPData) bool {
  1528. return server.lookupAllowTactic(clientGeoIPData, parameters.InproxyAllowDomainFrontedDestinations)
  1529. }
  1530. // inproxyBrokerGetTactics is a callback used by the in-proxy broker to
  1531. // provide tactics to proxies.
  1532. //
  1533. // The proxy sends its current tactics tag in apiParameters, and, when there
  1534. // are new tactics, inproxyBrokerGetTactics returns the payload and the new
  1535. // tactics tag. The broker should log new_tactics_tag in its ProxyAnnounce
  1536. // handler.
  1537. func (server *MeekServer) inproxyBrokerGetTactics(
  1538. geoIPData common.GeoIPData,
  1539. apiParameters common.APIParameters) ([]byte, string, error) {
  1540. tacticsPayload, err := server.support.TacticsServer.GetTacticsPayload(
  1541. geoIPData, apiParameters)
  1542. if err != nil {
  1543. return nil, "", errors.Trace(err)
  1544. }
  1545. var marshaledTacticsPayload []byte
  1546. newTacticsTag := ""
  1547. if tacticsPayload != nil {
  1548. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  1549. if err != nil {
  1550. return nil, "", errors.Trace(err)
  1551. }
  1552. if len(tacticsPayload.Tactics) > 0 {
  1553. newTacticsTag = tacticsPayload.Tag
  1554. }
  1555. }
  1556. return marshaledTacticsPayload, newTacticsTag, nil
  1557. }
  1558. // inproxyBrokerHandler reads an in-proxy broker session protocol message from
  1559. // the HTTP request body, dispatches the message to the broker, and writes
  1560. // the broker session response message to the HTTP response body.
  1561. //
  1562. // The HTTP response write timeout may be extended be the broker, as required.
  1563. // Error cases can return without writing any HTTP response. The caller
  1564. // should invoke server.handleError when an error is returned.
  1565. func (server *MeekServer) inproxyBrokerHandler(
  1566. clientIP string,
  1567. geoIPData common.GeoIPData,
  1568. w http.ResponseWriter,
  1569. r *http.Request) (retErr error) {
  1570. // Don't read more than MEEK_ENDPOINT_MAX_REQUEST_PAYLOAD_LENGTH bytes, as
  1571. // a sanity check and defense against potential resource exhaustion.
  1572. packet, err := ioutil.ReadAll(http.MaxBytesReader(
  1573. w, r.Body, MEEK_ENDPOINT_MAX_REQUEST_PAYLOAD_LENGTH))
  1574. if err != nil {
  1575. return errors.Trace(err)
  1576. }
  1577. extendTimeout := func(timeout time.Duration) {
  1578. // Extend the HTTP response write timeout to accomodate the timeout
  1579. // specified by the broker, such as in the case of the ProxyAnnounce
  1580. // request long poll. The base httpClientIOTimeout value is added, as
  1581. // it covers HTTP transport network operations, which are not
  1582. // necessarily included in the broker's timeouts.
  1583. //
  1584. // Note that any existing write timeout of httpClientIOTimeout would
  1585. // have been set before the body read, which may have consumed time,
  1586. // so adding the full httpClientIOTimeout value again may exceed the
  1587. // original httpClientIOTimeout target.
  1588. http.NewResponseController(w).SetWriteDeadline(
  1589. time.Now().Add(server.httpClientIOTimeout + timeout))
  1590. }
  1591. // Per https://pkg.go.dev/net/http#Request.Context, the request context is
  1592. // canceled when the client's connection closes or an HTTP/2 request is
  1593. // canceled. So it is expected that the broker operation will abort and
  1594. // stop waiting (in the case of long polling) if the client disconnects
  1595. // for any reason before a response is sent.
  1596. //
  1597. // When fronted by a CDN using persistent connections used to multiplex
  1598. // many clients, it is expected that CDNs will perform an HTTP/3 request
  1599. // cancellation in this scenario.
  1600. transportLogFields := common.LogFields{
  1601. "meek_server_http_version": r.Proto,
  1602. }
  1603. packet, err = server.inproxyBroker.HandleSessionPacket(
  1604. r.Context(),
  1605. extendTimeout,
  1606. transportLogFields,
  1607. clientIP,
  1608. geoIPData,
  1609. packet)
  1610. if err != nil {
  1611. return errors.Trace(err)
  1612. }
  1613. w.WriteHeader(http.StatusOK)
  1614. _, err = w.Write(packet)
  1615. if err != nil {
  1616. return errors.Trace(err)
  1617. }
  1618. return nil
  1619. }
  1620. type meekSession struct {
  1621. // Note: 64-bit ints used with atomic operations are placed
  1622. // at the start of struct to ensure 64-bit alignment.
  1623. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  1624. lastActivity int64
  1625. requestCount int64
  1626. metricClientRetries int64
  1627. metricPeakResponseSize int64
  1628. metricPeakCachedResponseSize int64
  1629. metricPeakCachedResponseHitSize int64
  1630. metricCachedResponseMissPosition int64
  1631. metricUnderlyingConnCount int64
  1632. lock sync.Mutex
  1633. deleted bool
  1634. underlyingConn net.Conn
  1635. clientConn *meekConn
  1636. meekProtocolVersion int
  1637. sessionIDSent bool
  1638. cachedResponse *CachedResponse
  1639. cookieName string
  1640. contentType string
  1641. httpVersion string
  1642. }
  1643. func (session *meekSession) touch() {
  1644. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  1645. }
  1646. func (session *meekSession) expired() bool {
  1647. if session.clientConn == nil {
  1648. // Not fully initialized. meekSession.clientConn will be set before adding
  1649. // the session to MeekServer.sessions.
  1650. return false
  1651. }
  1652. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  1653. return monotime.Since(lastActivity) >
  1654. session.clientConn.meekServer.maxSessionStaleness
  1655. }
  1656. // delete releases all resources allocated by a session.
  1657. func (session *meekSession) delete(haveLock bool) {
  1658. // TODO: close the persistent HTTP client connection, if one exists?
  1659. // This final call session.cachedResponse.Reset releases shared resources.
  1660. //
  1661. // This call requires exclusive access. session.lock is be obtained before
  1662. // calling session.cachedResponse.Reset. Once the lock is obtained, no
  1663. // request for this session is being processed concurrently, and pending
  1664. // requests will block at session.lock.
  1665. //
  1666. // This logic assumes that no further session.cachedResponse access occurs,
  1667. // or else resources may deplete (buffers won't be returned to the pool).
  1668. // These requirements are achieved by obtaining the lock, setting
  1669. // session.deleted, and any subsequent request handlers checking
  1670. // session.deleted immediately after obtaining the lock.
  1671. //
  1672. // session.lock.Lock may block for up to MEEK_HTTP_CLIENT_IO_TIMEOUT,
  1673. // the timeout for any active request handler processing a session
  1674. // request.
  1675. //
  1676. // When the lock must be acquired, clientConn.Close is called first, to
  1677. // interrupt any existing request handler blocking on pumpReads or pumpWrites.
  1678. session.clientConn.Close()
  1679. if !haveLock {
  1680. session.lock.Lock()
  1681. }
  1682. // Release all extended buffers back to the pool.
  1683. // session.cachedResponse.Reset is not safe for concurrent calls.
  1684. session.cachedResponse.Reset()
  1685. session.deleted = true
  1686. if !haveLock {
  1687. session.lock.Unlock()
  1688. }
  1689. }
  1690. // GetMetrics implements the common.MetricsSource interface.
  1691. func (session *meekSession) GetMetrics() common.LogFields {
  1692. logFields := make(common.LogFields)
  1693. logFields["meek_client_retries"] = atomic.LoadInt64(&session.metricClientRetries)
  1694. logFields["meek_peak_response_size"] = atomic.LoadInt64(&session.metricPeakResponseSize)
  1695. logFields["meek_peak_cached_response_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseSize)
  1696. logFields["meek_peak_cached_response_hit_size"] = atomic.LoadInt64(&session.metricPeakCachedResponseHitSize)
  1697. logFields["meek_cached_response_miss_position"] = atomic.LoadInt64(&session.metricCachedResponseMissPosition)
  1698. logFields["meek_underlying_connection_count"] = atomic.LoadInt64(&session.metricUnderlyingConnCount)
  1699. logFields["meek_cookie_name"] = session.cookieName
  1700. logFields["meek_content_type"] = session.contentType
  1701. logFields["meek_server_http_version"] = session.httpVersion
  1702. return logFields
  1703. }
  1704. // makeMeekSessionID creates a new session ID. The variable size is intended to
  1705. // frustrate traffic analysis of both plaintext and TLS meek traffic.
  1706. func makeMeekSessionID() (string, error) {
  1707. size := MEEK_MIN_SESSION_ID_LENGTH +
  1708. prng.Intn(MEEK_MAX_SESSION_ID_LENGTH-MEEK_MIN_SESSION_ID_LENGTH)
  1709. sessionID, err := common.MakeSecureRandomBytes(size)
  1710. if err != nil {
  1711. return "", errors.Trace(err)
  1712. }
  1713. // Omit padding to maximize variable size space. To the client, the session
  1714. // ID is an opaque string cookie value.
  1715. return base64.RawStdEncoding.EncodeToString(sessionID), nil
  1716. }
  1717. // meekConn implements the net.Conn interface and is to be used as a client
  1718. // connection by the tunnel server (being passed to sshServer.handleClient).
  1719. // meekConn bridges net/http request/response payload readers and writers
  1720. // and goroutines calling Read()s and Write()s.
  1721. type meekConn struct {
  1722. meekServer *MeekServer
  1723. meekSession *meekSession
  1724. firstUnderlyingConn net.Conn
  1725. remoteAddr net.Addr
  1726. protocolVersion int
  1727. closeBroadcast chan struct{}
  1728. closed int32
  1729. lastReadChecksum *uint64
  1730. readLock sync.Mutex
  1731. emptyReadBuffer chan *bytes.Buffer
  1732. partialReadBuffer chan *bytes.Buffer
  1733. fullReadBuffer chan *bytes.Buffer
  1734. writeLock sync.Mutex
  1735. nextWriteBuffer chan []byte
  1736. writeResult chan error
  1737. }
  1738. func newMeekConn(
  1739. meekServer *MeekServer,
  1740. meekSession *meekSession,
  1741. underlyingConn net.Conn,
  1742. remoteAddr net.Addr,
  1743. protocolVersion int) *meekConn {
  1744. // In order to inspect its properties, meekConn will hold a reference to
  1745. // firstUnderlyingConn, the _first_ underlying TCP conn, for the full
  1746. // lifetime of meekConn, which may exceed the lifetime of firstUnderlyingConn
  1747. // and include subsequent underlying TCP conns. In this case, it is expected
  1748. // that firstUnderlyingConn will be closed by "net/http", so no OS resources
  1749. // (e.g., a socket) are retained longer than necessary.
  1750. conn := &meekConn{
  1751. meekServer: meekServer,
  1752. meekSession: meekSession,
  1753. firstUnderlyingConn: underlyingConn,
  1754. remoteAddr: remoteAddr,
  1755. protocolVersion: protocolVersion,
  1756. closeBroadcast: make(chan struct{}),
  1757. closed: 0,
  1758. emptyReadBuffer: make(chan *bytes.Buffer, 1),
  1759. partialReadBuffer: make(chan *bytes.Buffer, 1),
  1760. fullReadBuffer: make(chan *bytes.Buffer, 1),
  1761. nextWriteBuffer: make(chan []byte, 1),
  1762. writeResult: make(chan error, 1),
  1763. }
  1764. // Read() calls and pumpReads() are synchronized by exchanging control
  1765. // of a single readBuffer. This is the same scheme used in and described
  1766. // in psiphon.MeekConn.
  1767. conn.emptyReadBuffer <- new(bytes.Buffer)
  1768. return conn
  1769. }
  1770. // GetMetrics implements the common.MetricsSource interface. The metrics are
  1771. // maintained in the meek session type; but logTunnel, which calls
  1772. // MetricsSource.GetMetrics, has a pointer only to this conn, so it calls
  1773. // through to the session.
  1774. func (conn *meekConn) GetMetrics() common.LogFields {
  1775. logFields := conn.meekSession.GetMetrics()
  1776. if conn.meekServer.passthroughAddress != "" {
  1777. logFields["passthrough_address"] = conn.meekServer.passthroughAddress
  1778. }
  1779. // Include metrics, such as fragmentor metrics, from the _first_ underlying
  1780. // TCP conn. Properties of subsequent underlying TCP conns are not reflected
  1781. // in these metrics; we assume that the first TCP conn, which most likely
  1782. // transits the various protocol handshakes, is most significant.
  1783. underlyingMetrics, ok := conn.firstUnderlyingConn.(common.MetricsSource)
  1784. if ok {
  1785. logFields.Add(underlyingMetrics.GetMetrics())
  1786. }
  1787. return logFields
  1788. }
  1789. // GetUnderlyingTCPAddrs implements the common.UnderlyingTCPAddrSource
  1790. // interface, returning the TCP addresses for the _first_ underlying TCP
  1791. // connection in the meek tunnel.
  1792. func (conn *meekConn) GetUnderlyingTCPAddrs() (*net.TCPAddr, *net.TCPAddr, bool) {
  1793. localAddr, ok := conn.firstUnderlyingConn.LocalAddr().(*net.TCPAddr)
  1794. if !ok {
  1795. return nil, nil, false
  1796. }
  1797. remoteAddr, ok := conn.firstUnderlyingConn.RemoteAddr().(*net.TCPAddr)
  1798. if !ok {
  1799. return nil, nil, false
  1800. }
  1801. return localAddr, remoteAddr, true
  1802. }
  1803. // SetReplay implements the common.FragmentorReplayAccessor interface, applying
  1804. // the inputs to the _first_ underlying TCP connection in the meek tunnel. If
  1805. // the underlying connection is closed, then SetSeed call will have no effect.
  1806. func (conn *meekConn) SetReplay(PRNG *prng.PRNG) {
  1807. underlyingConn := conn.firstUnderlyingConn
  1808. if conn.meekServer.normalizer != nil {
  1809. // The underlying conn is wrapped with a normalizer.
  1810. normalizer, ok := underlyingConn.(*transforms.HTTPNormalizer)
  1811. if ok {
  1812. underlyingConn = normalizer.Conn
  1813. }
  1814. }
  1815. fragmentor, ok := underlyingConn.(common.FragmentorAccessor)
  1816. if ok {
  1817. fragmentor.SetReplay(PRNG)
  1818. }
  1819. }
  1820. // GetReplay implements the FragmentorReplayAccessor interface, getting the
  1821. // outputs from the _first_ underlying TCP connection in the meek tunnel.
  1822. //
  1823. // We assume that the first TCP conn is most significant: the initial TCP
  1824. // connection most likely fragments protocol handshakes; and, in the case the
  1825. // packet manipulation, any selected packet manipulation spec would have been
  1826. // successful.
  1827. func (conn *meekConn) GetReplay() (*prng.Seed, bool) {
  1828. underlyingConn := conn.firstUnderlyingConn
  1829. if conn.meekServer.normalizer != nil {
  1830. // The underlying conn is wrapped with a normalizer.
  1831. normalizer, ok := underlyingConn.(*transforms.HTTPNormalizer)
  1832. if ok {
  1833. underlyingConn = normalizer.Conn
  1834. }
  1835. }
  1836. fragmentor, ok := underlyingConn.(common.FragmentorAccessor)
  1837. if ok {
  1838. return fragmentor.GetReplay()
  1839. }
  1840. return nil, false
  1841. }
  1842. func (conn *meekConn) StopFragmenting() {
  1843. fragmentor, ok := conn.firstUnderlyingConn.(common.FragmentorAccessor)
  1844. if ok {
  1845. fragmentor.StopFragmenting()
  1846. }
  1847. }
  1848. // pumpReads causes goroutines blocking on meekConn.Read() to read
  1849. // from the specified reader. This function blocks until the reader
  1850. // is fully consumed or the meekConn is closed. A read buffer allows
  1851. // up to MEEK_MAX_REQUEST_PAYLOAD_LENGTH bytes to be read and buffered
  1852. // without a Read() immediately consuming the bytes, but there's still
  1853. // a possibility of a stall if no Read() calls are made after this
  1854. // read buffer is full.
  1855. // Returns the number of request bytes read.
  1856. // Note: assumes only one concurrent call to pumpReads
  1857. func (conn *meekConn) pumpReads(reader io.Reader) (int64, error) {
  1858. // Use either an empty or partial buffer. By using a partial
  1859. // buffer, pumpReads will not block if the Read() caller has
  1860. // not fully drained the read buffer.
  1861. var readBuffer *bytes.Buffer
  1862. select {
  1863. case readBuffer = <-conn.emptyReadBuffer:
  1864. case readBuffer = <-conn.partialReadBuffer:
  1865. case <-conn.closeBroadcast:
  1866. return 0, io.EOF
  1867. }
  1868. newDataOffset := readBuffer.Len()
  1869. // Since we need to read the full request payload in order to
  1870. // take its checksum before relaying it, the read buffer can
  1871. // grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
  1872. // +1 allows for an explicit check for request payloads that
  1873. // exceed the maximum permitted length.
  1874. limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
  1875. n, err := readBuffer.ReadFrom(limitReader)
  1876. if err == nil && n == MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1 {
  1877. err = std_errors.New("invalid request payload length")
  1878. }
  1879. // If the request read fails, don't relay the new data. This allows
  1880. // the client to retry and resend its request payload without
  1881. // interrupting/duplicating the payload flow.
  1882. if err != nil {
  1883. readBuffer.Truncate(newDataOffset)
  1884. conn.replaceReadBuffer(readBuffer)
  1885. return 0, errors.Trace(err)
  1886. }
  1887. // Check if request payload checksum matches immediately
  1888. // previous payload. On match, assume this is a client retry
  1889. // sending payload that was already relayed and skip this
  1890. // payload. Payload is OSSH ciphertext and almost surely
  1891. // will not repeat. In the highly unlikely case that it does,
  1892. // the underlying SSH connection will fail and the client
  1893. // must reconnect.
  1894. checksum := crc64.Checksum(
  1895. readBuffer.Bytes()[newDataOffset:], conn.meekServer.checksumTable)
  1896. if conn.lastReadChecksum == nil {
  1897. conn.lastReadChecksum = new(uint64)
  1898. } else if *conn.lastReadChecksum == checksum {
  1899. readBuffer.Truncate(newDataOffset)
  1900. }
  1901. *conn.lastReadChecksum = checksum
  1902. conn.replaceReadBuffer(readBuffer)
  1903. return n, nil
  1904. }
  1905. var errMeekConnectionHasClosed = std_errors.New("meek connection has closed")
  1906. // Read reads from the meekConn into buffer. Read blocks until
  1907. // some data is read or the meekConn closes. Under the hood, it
  1908. // waits for pumpReads to submit a reader to read from.
  1909. // Note: lock is to conform with net.Conn concurrency semantics
  1910. func (conn *meekConn) Read(buffer []byte) (int, error) {
  1911. conn.readLock.Lock()
  1912. defer conn.readLock.Unlock()
  1913. var readBuffer *bytes.Buffer
  1914. select {
  1915. case readBuffer = <-conn.partialReadBuffer:
  1916. case readBuffer = <-conn.fullReadBuffer:
  1917. case <-conn.closeBroadcast:
  1918. return 0, errors.Trace(errMeekConnectionHasClosed)
  1919. }
  1920. n, err := readBuffer.Read(buffer)
  1921. conn.replaceReadBuffer(readBuffer)
  1922. return n, err
  1923. }
  1924. func (conn *meekConn) replaceReadBuffer(readBuffer *bytes.Buffer) {
  1925. length := readBuffer.Len()
  1926. if length >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1927. conn.fullReadBuffer <- readBuffer
  1928. } else if length == 0 {
  1929. conn.emptyReadBuffer <- readBuffer
  1930. } else {
  1931. conn.partialReadBuffer <- readBuffer
  1932. }
  1933. }
  1934. // pumpWrites causes goroutines blocking on meekConn.Write() to write
  1935. // to the specified writer. This function blocks until the meek response
  1936. // body limits (size for protocol v1, turn around time for protocol v2+)
  1937. // are met, or the meekConn is closed.
  1938. //
  1939. // Note: channel scheme assumes only one concurrent call to pumpWrites
  1940. func (conn *meekConn) pumpWrites(
  1941. writer io.Writer, skipExtendedTurnAround bool) (int, error) {
  1942. startTime := time.Now()
  1943. timeout := time.NewTimer(conn.meekServer.turnAroundTimeout)
  1944. defer timeout.Stop()
  1945. n := 0
  1946. for {
  1947. select {
  1948. case buffer := <-conn.nextWriteBuffer:
  1949. written, err := writer.Write(buffer)
  1950. n += written
  1951. // Assumes that writeResult won't block.
  1952. // Note: always send the err to writeResult,
  1953. // as the Write() caller is blocking on this.
  1954. conn.writeResult <- err
  1955. if err != nil {
  1956. return n, err
  1957. }
  1958. if conn.protocolVersion < MEEK_PROTOCOL_VERSION_1 {
  1959. // Pre-protocol version 1 clients expect at most
  1960. // MEEK_MAX_REQUEST_PAYLOAD_LENGTH response bodies
  1961. return n, nil
  1962. }
  1963. if skipExtendedTurnAround {
  1964. // When fast turn around is indicated, skip the extended turn
  1965. // around timeout. This optimizes for upstream flows.
  1966. return n, nil
  1967. }
  1968. totalElapsedTime := time.Since(startTime) / time.Millisecond
  1969. if totalElapsedTime >= conn.meekServer.extendedTurnAroundTimeout {
  1970. return n, nil
  1971. }
  1972. timeout.Reset(conn.meekServer.turnAroundTimeout)
  1973. case <-timeout.C:
  1974. return n, nil
  1975. case <-conn.closeBroadcast:
  1976. return n, errors.Trace(errMeekConnectionHasClosed)
  1977. }
  1978. }
  1979. }
  1980. // Write writes the buffer to the meekConn. It blocks until the
  1981. // entire buffer is written to or the meekConn closes. Under the
  1982. // hood, it waits for sufficient pumpWrites calls to consume the
  1983. // write buffer.
  1984. // Note: lock is to conform with net.Conn concurrency semantics
  1985. func (conn *meekConn) Write(buffer []byte) (int, error) {
  1986. conn.writeLock.Lock()
  1987. defer conn.writeLock.Unlock()
  1988. // TODO: may be more efficient to send whole buffer
  1989. // and have pumpWrites stash partial buffer when can't
  1990. // send it all.
  1991. n := 0
  1992. for n < len(buffer) {
  1993. end := n + MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1994. if end > len(buffer) {
  1995. end = len(buffer)
  1996. }
  1997. // Only write MEEK_MAX_REQUEST_PAYLOAD_LENGTH at a time,
  1998. // to ensure compatibility with v1 protocol.
  1999. chunk := buffer[n:end]
  2000. select {
  2001. case conn.nextWriteBuffer <- chunk:
  2002. case <-conn.closeBroadcast:
  2003. return n, errors.Trace(errMeekConnectionHasClosed)
  2004. }
  2005. // Wait for the buffer to be processed.
  2006. select {
  2007. case <-conn.writeResult:
  2008. // The err from conn.writeResult comes from the
  2009. // io.MultiWriter used in pumpWrites, which writes
  2010. // to both the cached response and the HTTP response.
  2011. //
  2012. // Don't stop on error here, since only writing
  2013. // to the HTTP response will fail, and the client
  2014. // may retry and use the cached response.
  2015. //
  2016. // It's possible that the cached response buffer
  2017. // is too small for the client to successfully
  2018. // retry, but that cannot be determined. In this
  2019. // case, the meek connection will eventually fail.
  2020. //
  2021. // err is already logged in ServeHTTP.
  2022. case <-conn.closeBroadcast:
  2023. return n, errors.Trace(errMeekConnectionHasClosed)
  2024. }
  2025. n += len(chunk)
  2026. }
  2027. return n, nil
  2028. }
  2029. // Close closes the meekConn. This will interrupt any blocked
  2030. // Read, Write, pumpReads, and pumpWrites.
  2031. func (conn *meekConn) Close() error {
  2032. if atomic.CompareAndSwapInt32(&conn.closed, 0, 1) {
  2033. close(conn.closeBroadcast)
  2034. // In general, we rely on "net/http" to close underlying TCP conns. In
  2035. // this case, we can directly close the first once, if it's still
  2036. // open. Don't close a persistent connection when fronted, as it may
  2037. // be still be used by other clients.
  2038. if !conn.meekServer.isFronted {
  2039. conn.firstUnderlyingConn.Close()
  2040. }
  2041. }
  2042. return nil
  2043. }
  2044. // Stub implementation of net.Conn.LocalAddr
  2045. func (conn *meekConn) LocalAddr() net.Addr {
  2046. return nil
  2047. }
  2048. // RemoteAddr returns the remoteAddr specified in newMeekConn. This
  2049. // acts as a proxy for the actual remote address, which is either a
  2050. // direct HTTP/HTTPS connection remote address, or in the case of
  2051. // downstream proxy of CDN fronts, some other value determined via
  2052. // HTTP headers.
  2053. func (conn *meekConn) RemoteAddr() net.Addr {
  2054. return conn.remoteAddr
  2055. }
  2056. // SetDeadline is not a true implementation of net.Conn.SetDeadline. It
  2057. // merely checks that the requested timeout exceeds the MEEK_MAX_SESSION_STALENESS
  2058. // period. When it does, and the session is idle, the meekConn Read/Write will
  2059. // be interrupted and return an error (not a timeout error) before the deadline.
  2060. // In other words, this conn will approximate the desired functionality of
  2061. // timing out on idle on or before the requested deadline.
  2062. func (conn *meekConn) SetDeadline(t time.Time) error {
  2063. // Overhead: nanoseconds (https://blog.cloudflare.com/its-go-time-on-linux/)
  2064. if time.Now().Add(conn.meekServer.maxSessionStaleness).Before(t) {
  2065. return nil
  2066. }
  2067. return errors.TraceNew("not supported")
  2068. }
  2069. // Stub implementation of net.Conn.SetReadDeadline
  2070. func (conn *meekConn) SetReadDeadline(t time.Time) error {
  2071. return errors.TraceNew("not supported")
  2072. }
  2073. // Stub implementation of net.Conn.SetWriteDeadline
  2074. func (conn *meekConn) SetWriteDeadline(t time.Time) error {
  2075. return errors.TraceNew("not supported")
  2076. }