meek.go 86 KB

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