meek.go 89 KB

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