meek.go 91 KB

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