meekConn.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "bytes"
  22. "context"
  23. "crypto/rand"
  24. "crypto/tls"
  25. "encoding/base64"
  26. "encoding/json"
  27. "fmt"
  28. "io"
  29. "io/ioutil"
  30. "net"
  31. "net/http"
  32. "net/url"
  33. "strings"
  34. "sync"
  35. "time"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  46. "golang.org/x/crypto/nacl/box"
  47. "golang.org/x/net/http2"
  48. )
  49. // MeekConn is based on meek-client.go from Tor:
  50. //
  51. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  52. // CC0 1.0 Universal
  53. const (
  54. MEEK_PROTOCOL_VERSION = 3
  55. MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
  56. )
  57. type MeekMode int
  58. const (
  59. MeekModeRelay = iota
  60. MeekModeObfuscatedRoundTrip
  61. MeekModePlaintextRoundTrip
  62. MeekModeWrappedPlaintextRoundTrip
  63. )
  64. // MeekConfig specifies the behavior of a MeekConn.
  65. type MeekConfig struct {
  66. // DiagnosticID is the server ID to record in any diagnostics notices.
  67. DiagnosticID string
  68. // Parameters is the active set of parameters.Parameters to use
  69. // for the meek dial.
  70. Parameters *parameters.Parameters
  71. // Mode selects the mode of operation:
  72. //
  73. // MeekModeRelay: encapsulates net.Conn flows in HTTP requests and responses;
  74. // secures and obfuscates metadata in an encrypted HTTP cookie, making it
  75. // suitable for non-TLS HTTP and HTTPS with unverifed server certificates;
  76. // the caller is responsible for securing and obfuscating the net.Conn flows;
  77. // the origin server should be a meek server; used for the meek tunnel
  78. // protocols.
  79. //
  80. // MeekModeObfuscatedRoundTrip: enables ObfuscatedRoundTrip, which performs
  81. // HTTP round trips; secures and obfuscates metadata, including the end point
  82. // (or path), in an encrypted HTTP cookie, making it suitable for non-TLS
  83. // HTTP and HTTPS with unverifed server certificates; the caller is
  84. // responsible for securing and obfuscating request/response payloads; the
  85. // origin server should be a meek server; used for tactics requests.
  86. //
  87. // MeekModePlaintextRoundTrip: enables RoundTrip; the MeekConn is an
  88. // http.RoundTripper; there are no security or obfuscation measures at the
  89. // HTTP level; TLS and server certificate verification is required; the
  90. // origin server may be any HTTP(S) server.
  91. //
  92. // MeekModeWrappedPlaintextRoundTrip: is equivalent to
  93. // MeekModePlaintextRoundTrip, except skipping of server certificate
  94. // verification is permitted. In this mode, the caller is asserting that
  95. // the HTTP plaintext payload is wrapped in its own transport security
  96. // layer.
  97. //
  98. // As with the other modes, MeekMode[Wrapped]PlaintextRoundTrip supports
  99. // HTTP/2 with utls, and integration with DialParameters for replay --
  100. // which are not otherwise implemented if using just CustomTLSDialer and
  101. // net.http.
  102. Mode MeekMode
  103. // DialAddress is the actual network address to dial to establish a
  104. // connection to the meek server. This may be either a fronted or
  105. // direct address. The address must be in the form "host:port",
  106. // where host may be a domain name or IP address.
  107. DialAddress string
  108. // UseQUIC indicates whether to use HTTP/2 over QUIC.
  109. UseQUIC bool
  110. // QUICVersion indicates which QUIC version to use.
  111. QUICVersion string
  112. // QUICClientHelloSeed is used for randomized QUIC Client Hellos.
  113. QUICClientHelloSeed *prng.Seed
  114. // QUICDisablePathMTUDiscovery indicates whether to disable path MTU
  115. // discovery in the QUIC client.
  116. QUICDisablePathMTUDiscovery bool
  117. // UseHTTPS indicates whether to use HTTPS (true) or HTTP (false).
  118. UseHTTPS bool
  119. // TLSProfile specifies the value for CustomTLSConfig.TLSProfile for all
  120. // underlying TLS connections created by this meek connection.
  121. TLSProfile string
  122. // TLSFragmentClientHello specifies whether to fragment the TLS Client Hello.
  123. TLSFragmentClientHello bool
  124. // LegacyPassthrough indicates that the server expects a legacy passthrough
  125. // message.
  126. LegacyPassthrough bool
  127. // NoDefaultTLSSessionID specifies the value for
  128. // CustomTLSConfig.NoDefaultTLSSessionID for all underlying TLS connections
  129. // created by this meek connection.
  130. NoDefaultTLSSessionID bool
  131. // RandomizedTLSProfileSeed specifies the value for
  132. // CustomTLSConfig.RandomizedTLSProfileSeed for all underlying TLS
  133. // connections created by this meek connection.
  134. RandomizedTLSProfileSeed *prng.Seed
  135. // UseObfuscatedSessionTickets indicates whether to use obfuscated session
  136. // tickets. Assumes UseHTTPS is true.
  137. // Ignored for MeekMode[Wrapped]PlaintextRoundTrip.
  138. UseObfuscatedSessionTickets bool
  139. // SNIServerName is the value to place in the TLS/QUIC SNI server_name field
  140. // when HTTPS or QUIC is used.
  141. SNIServerName string
  142. // HostHeader is the value to place in the HTTP request Host header.
  143. HostHeader string
  144. // TransformedHostName records whether a hostname transformation is
  145. // in effect. This value is used for stats reporting.
  146. TransformedHostName bool
  147. // AddPsiphonFrontingHeader specifies whether to add the
  148. // X-Psiphon-Fronting-Address custom header.
  149. AddPsiphonFrontingHeader bool
  150. // VerifyServerName specifies a domain name that must appear in the server
  151. // certificate. When blank, server certificate verification is disabled.
  152. VerifyServerName string
  153. // VerifyPins specifies one or more certificate pin values, one of which must
  154. // appear in the verified server certificate chain. A pin value is the
  155. // base64-encoded SHA2 digest of a certificate's public key. When specified,
  156. // at least one pin must match at least one certificate in the chain, at any
  157. // position; e.g., the root CA may be pinned, or the server certificate,
  158. // etc.
  159. VerifyPins []string
  160. // DisableSystemRootCAs, when true, disables loading system root CAs when
  161. // verifying the server certificate chain. Set DisableSystemRootCAs only in
  162. // cases where system root CAs cannot be loaded and there is additional
  163. // security at the payload level; for example, if unsupported (iOS < 12) or
  164. // insufficient memory (VPN extension on iOS < 15).
  165. //
  166. // When DisableSystemRootCAs is set, both VerifyServerName and VerifyPins
  167. // must not be set.
  168. DisableSystemRootCAs bool
  169. // ClientTunnelProtocol is the protocol the client is using. It's included in
  170. // the meek cookie for optional use by the server, in cases where the server
  171. // cannot unambiguously determine the tunnel protocol. ClientTunnelProtocol
  172. // is used when selecting tactics targeted at specific protocols.
  173. // Ignored for MeekMode[Wrapped]PlaintextRoundTrip.
  174. ClientTunnelProtocol string
  175. // NetworkLatencyMultiplier specifies a custom network latency multiplier to
  176. // apply to client parameters used by this meek connection.
  177. NetworkLatencyMultiplier float64
  178. // The following values are used to create the obfuscated meek cookie.
  179. // Ignored for MeekMode[Wrapped]PlaintextRoundTrip.
  180. MeekCookieEncryptionPublicKey string
  181. MeekObfuscatedKey string
  182. MeekObfuscatorPaddingSeed *prng.Seed
  183. // HTTPTransformerParameters specifies an HTTP transformer to apply to the
  184. // meek connection if it uses HTTP.
  185. HTTPTransformerParameters *transforms.HTTPTransformerParameters
  186. // AdditionalHeaders is a set of additional arbitrary HTTP headers that
  187. // are added to all meek HTTP requests. An additional header is ignored
  188. // when the header name is already present in a meek request.
  189. AdditionalHeaders http.Header
  190. }
  191. // MeekConn is a network connection that tunnels net.Conn flows over HTTP and supports
  192. // "domain fronting". Meek sends client->server flow in HTTP request bodies and
  193. // receives server->client flow in HTTP response bodies. Polling is used to
  194. // approximate full duplex TCP. MeekConn also offers HTTP round trip modes.
  195. //
  196. // Domain fronting is a network obfuscation technique in which the connection to a web
  197. // server, typically a CDN, is indistinguishable from any other HTTPS
  198. // connection to the generic "fronting domain" -- the HTTP Host header is used
  199. // to route the requests to the actual destination. See
  200. // https://trac.torproject.org/projects/tor/wiki/doc/meek for more details.
  201. //
  202. // MeekConn also support unfronted operation, in which connections are made
  203. // without routing through a CDN; and plain HTTP operation, without TLS or
  204. // QUIC, with connection metadata obfuscated in HTTP cookies.
  205. type MeekConn struct {
  206. params *parameters.Parameters
  207. mode MeekMode
  208. networkLatencyMultiplier float64
  209. isQUIC bool
  210. url *url.URL
  211. additionalHeaders http.Header
  212. cookie *http.Cookie
  213. contentType string
  214. cookieSize int
  215. tlsPadding int
  216. limitRequestPayloadLength int
  217. redialTLSProbability float64
  218. transport transporter
  219. connManager *meekUnderlyingConnManager
  220. mutex sync.Mutex
  221. isClosed bool
  222. runCtx context.Context
  223. stopRunning context.CancelFunc
  224. relayWaitGroup *sync.WaitGroup
  225. // For MeekModeObfuscatedRoundTrip
  226. meekCookieEncryptionPublicKey string
  227. meekObfuscatedKey string
  228. meekObfuscatorPaddingSeed *prng.Seed
  229. clientTunnelProtocol string
  230. // For MeekModeRelay
  231. fullReceiveBufferLength int
  232. readPayloadChunkLength int
  233. emptyReceiveBuffer chan *bytes.Buffer
  234. partialReceiveBuffer chan *bytes.Buffer
  235. fullReceiveBuffer chan *bytes.Buffer
  236. emptySendBuffer chan *bytes.Buffer
  237. partialSendBuffer chan *bytes.Buffer
  238. fullSendBuffer chan *bytes.Buffer
  239. }
  240. func (conn *MeekConn) getCustomParameters() parameters.ParametersAccessor {
  241. return conn.params.GetCustom(conn.networkLatencyMultiplier)
  242. }
  243. // transporter is implemented by both http.Transport and upstreamproxy.ProxyAuthTransport.
  244. type transporter interface {
  245. CloseIdleConnections()
  246. RoundTrip(req *http.Request) (resp *http.Response, err error)
  247. }
  248. // DialMeek returns an initialized meek connection. A meek connection is
  249. // an HTTP session which does not depend on an underlying socket connection (although
  250. // persistent HTTP connections are used for performance). This function may not
  251. // wait for the connection to be established before returning.
  252. func DialMeek(
  253. ctx context.Context,
  254. meekConfig *MeekConfig,
  255. dialConfig *DialConfig) (*MeekConn, error) {
  256. if meekConfig.UseQUIC && meekConfig.UseHTTPS {
  257. return nil, errors.TraceNew(
  258. "invalid config: only one of UseQUIC or UseHTTPS may be set")
  259. }
  260. if meekConfig.UseQUIC &&
  261. (meekConfig.VerifyServerName != "" || len(meekConfig.VerifyPins) > 0) {
  262. // TODO: UseQUIC VerifyServerName and VerifyPins support (required for MeekModePlaintextRoundTrip).
  263. return nil, errors.TraceNew(
  264. "invalid config: VerifyServerName and VerifyPins not supported for UseQUIC")
  265. }
  266. skipVerify := meekConfig.VerifyServerName == ""
  267. if len(meekConfig.VerifyPins) > 0 && skipVerify {
  268. return nil, errors.TraceNew(
  269. "invalid config: VerifyServerName must be set when VerifyPins is set")
  270. }
  271. if meekConfig.DisableSystemRootCAs &&
  272. (len(meekConfig.VerifyServerName) > 0 || len(meekConfig.VerifyPins) > 0) {
  273. return nil, errors.TraceNew(
  274. "invalid config: VerifyServerName and VerifyPins must not be set when DisableSystemRootCAs is set")
  275. }
  276. if meekConfig.Mode == MeekModePlaintextRoundTrip &&
  277. (!meekConfig.UseHTTPS || (skipVerify && !meekConfig.DisableSystemRootCAs)) {
  278. return nil, errors.TraceNew(
  279. "invalid config: MeekModePlaintextRoundTrip requires UseHTTPS and VerifyServerName when system root CAs can be loaded")
  280. }
  281. runCtx, stopRunning := context.WithCancel(context.Background())
  282. meek := &MeekConn{
  283. params: meekConfig.Parameters,
  284. mode: meekConfig.Mode,
  285. networkLatencyMultiplier: meekConfig.NetworkLatencyMultiplier,
  286. isClosed: false,
  287. runCtx: runCtx,
  288. stopRunning: stopRunning,
  289. relayWaitGroup: new(sync.WaitGroup),
  290. }
  291. cleanupStopRunning := true
  292. cleanupConns := true
  293. // Cleanup in error cases
  294. defer func() {
  295. if cleanupStopRunning {
  296. meek.stopRunning()
  297. }
  298. if cleanupConns && meek.connManager != nil {
  299. meek.connManager.closeAll()
  300. }
  301. }()
  302. if meek.mode == MeekModeRelay {
  303. var err error
  304. meek.cookie,
  305. meek.contentType,
  306. meek.tlsPadding,
  307. meek.limitRequestPayloadLength,
  308. meek.redialTLSProbability,
  309. err =
  310. makeMeekObfuscationValues(
  311. meek.getCustomParameters(),
  312. meekConfig.MeekCookieEncryptionPublicKey,
  313. meekConfig.MeekObfuscatedKey,
  314. meekConfig.MeekObfuscatorPaddingSeed,
  315. meekConfig.ClientTunnelProtocol,
  316. "")
  317. if err != nil {
  318. return nil, errors.Trace(err)
  319. }
  320. // For stats, record the size of the initial obfuscated cookie.
  321. meek.cookieSize = len(meek.cookie.Name) + len(meek.cookie.Value)
  322. }
  323. // Configure transport: QUIC or HTTPS or HTTP
  324. var (
  325. scheme string
  326. opaqueURL string
  327. transport transporter
  328. additionalHeaders http.Header
  329. proxyUrl func(*http.Request) (*url.URL, error)
  330. )
  331. if meekConfig.UseQUIC {
  332. meek.isQUIC = true
  333. scheme = "https"
  334. udpDialer := func(ctx context.Context) (net.PacketConn, *net.UDPAddr, error) {
  335. packetConn, remoteAddr, err := NewUDPConn(
  336. ctx, "udp", false, "", meekConfig.DialAddress, dialConfig)
  337. if err != nil {
  338. return nil, nil, errors.Trace(err)
  339. }
  340. return packetConn, remoteAddr, nil
  341. }
  342. meek.connManager = newMeekUnderlyingConnManager(nil, nil, udpDialer)
  343. var err error
  344. transport, err = quic.NewQUICTransporter(
  345. ctx,
  346. func(message string) {
  347. NoticeInfo(message)
  348. },
  349. meek.connManager.dialPacketConn,
  350. meekConfig.SNIServerName,
  351. meekConfig.QUICVersion,
  352. meekConfig.QUICClientHelloSeed,
  353. meekConfig.QUICDisablePathMTUDiscovery)
  354. if err != nil {
  355. return nil, errors.Trace(err)
  356. }
  357. } else if meekConfig.UseHTTPS {
  358. // Custom TLS dialer:
  359. //
  360. // 1. ignores the HTTP request address and uses the fronting domain
  361. // 2. optionally disables SNI -- SNI breaks fronting when used with certain CDNs.
  362. // 3. may skip verifying the server cert.
  363. //
  364. // Reasoning for #3:
  365. //
  366. // With a TLS MiM attack in place, and server certs verified, we'll fail to connect because the client
  367. // will refuse to connect. That's not a successful outcome.
  368. //
  369. // With a MiM attack in place, and server certs not verified, we'll fail to connect if the MiM is actively
  370. // targeting Psiphon and classifying the HTTP traffic by Host header or payload signature.
  371. //
  372. // However, in the case of a passive MiM that's just recording traffic or an active MiM that's targeting
  373. // something other than Psiphon, the client will connect. This is a successful outcome.
  374. //
  375. // What is exposed to the MiM? The Host header does not contain a Psiphon server IP address, just an
  376. // unrelated, randomly generated domain name which cannot be used to block direct connections. The
  377. // Psiphon server IP is sent over meek, but it's in the encrypted cookie.
  378. //
  379. // The payload (user traffic) gets its confidentiality and integrity from the underlying SSH protocol.
  380. // So, nothing is leaked to the MiM apart from signatures which could be used to classify the traffic
  381. // as Psiphon to possibly block it; but note that not revealing that the client is Psiphon is outside
  382. // our threat model; we merely seek to evade mass blocking by taking steps that require progressively
  383. // more effort to block.
  384. //
  385. // There is a subtle attack remaining: an adversary that can MiM some CDNs but not others (and so can
  386. // classify Psiphon traffic on some CDNs but not others) may throttle non-MiM CDNs so that our server
  387. // selection always chooses tunnels to the MiM CDN (without any server cert verification, we won't
  388. // exclusively connect to non-MiM CDNs); then the adversary kills the underlying TCP connection after
  389. // some short period. This is partially mitigated by tactics mechanisms.
  390. scheme = "https"
  391. tlsConfig := &CustomTLSConfig{
  392. Parameters: meekConfig.Parameters,
  393. DialAddr: meekConfig.DialAddress,
  394. Dial: NewTCPDialer(dialConfig),
  395. SNIServerName: meekConfig.SNIServerName,
  396. SkipVerify: skipVerify,
  397. VerifyServerName: meekConfig.VerifyServerName,
  398. VerifyPins: meekConfig.VerifyPins,
  399. DisableSystemRootCAs: meekConfig.DisableSystemRootCAs,
  400. TLSProfile: meekConfig.TLSProfile,
  401. NoDefaultTLSSessionID: &meekConfig.NoDefaultTLSSessionID,
  402. RandomizedTLSProfileSeed: meekConfig.RandomizedTLSProfileSeed,
  403. TLSPadding: meek.tlsPadding,
  404. TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
  405. FragmentClientHello: meekConfig.TLSFragmentClientHello,
  406. }
  407. tlsConfig.EnableClientSessionCache()
  408. if meekConfig.UseObfuscatedSessionTickets {
  409. tlsConfig.ObfuscatedSessionTicketKey = meekConfig.MeekObfuscatedKey
  410. }
  411. if meekConfig.Mode != MeekModePlaintextRoundTrip &&
  412. meekConfig.Mode != MeekModeWrappedPlaintextRoundTrip &&
  413. meekConfig.MeekObfuscatedKey != "" {
  414. // As the passthrough message is unique and indistinguishable from a normal
  415. // TLS client random value, we set it unconditionally and not just for
  416. // protocols which may support passthrough (even for those protocols,
  417. // clients don't know which servers are configured to use it).
  418. passthroughMessage, err := obfuscator.MakeTLSPassthroughMessage(
  419. !meekConfig.LegacyPassthrough,
  420. meekConfig.MeekObfuscatedKey)
  421. if err != nil {
  422. return nil, errors.Trace(err)
  423. }
  424. tlsConfig.PassthroughMessage = passthroughMessage
  425. }
  426. tlsDialer := NewCustomTLSDialer(tlsConfig)
  427. // Pre-dial one TLS connection in order to inspect the negotiated
  428. // application protocol. Then we create an HTTP/2 or HTTP/1.1 transport
  429. // depending on which protocol was negotiated. The TLS dialer
  430. // is assumed to negotiate only "h2" or "http/1.1"; or not negotiate
  431. // an application protocol.
  432. //
  433. // We cannot rely on net/http's HTTP/2 support since it's only
  434. // activated when http.Transport.DialTLS returns a golang crypto/tls.Conn;
  435. // e.g., https://github.com/golang/go/blob/c8aec4095e089ff6ac50d18e97c3f46561f14f48/src/net/http/transport.go#L1040
  436. //
  437. // The pre-dialed connection is stored in a cachedTLSDialer, which will
  438. // return the cached pre-dialed connection to its first Dial caller, and
  439. // use the tlsDialer for all other Dials.
  440. //
  441. // cachedTLSDialer.close() must be called on all exits paths from this
  442. // function and in meek.Close() to ensure the cached conn is closed in
  443. // any case where no Dial call is made.
  444. //
  445. // The pre-dial must be interruptible so that DialMeek doesn't block and
  446. // hang/delay a shutdown or end of establishment. So the pre-dial uses
  447. // the Controller's PendingConns, not the MeekConn PendingConns. For this
  448. // purpose, a special preDialer is configured.
  449. //
  450. // Only one pre-dial attempt is made; there are no retries. This differs
  451. // from relayRoundTrip, which retries and may redial for each retry.
  452. // Retries at the pre-dial phase are less useful since there's no active
  453. // session to preserve, and establishment will simply try another server.
  454. // Note that the underlying TCPDial may still try multiple IP addreses when
  455. // the destination is a domain and it resolves to multiple IP adresses.
  456. //
  457. // The pre-dial is made within the parent dial context, so that DialMeek
  458. // may be interrupted. Subsequent dials are made within the meek round trip
  459. // request context.
  460. // As DialAddr is set in the CustomTLSConfig, no address is required here.
  461. preConn, err := tlsDialer(ctx, "tcp", "")
  462. if err != nil {
  463. return nil, errors.Trace(err)
  464. }
  465. meek.connManager = newMeekUnderlyingConnManager(preConn, tlsDialer, nil)
  466. if IsTLSConnUsingHTTP2(preConn) {
  467. NoticeInfo("negotiated HTTP/2 for %s", meekConfig.DiagnosticID)
  468. transport = &http2.Transport{
  469. DialTLSContext: func(
  470. ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
  471. return meek.connManager.dial(ctx, network, addr)
  472. },
  473. }
  474. } else {
  475. transport = &http.Transport{
  476. DialTLSContext: meek.connManager.dial,
  477. }
  478. }
  479. } else {
  480. scheme = "http"
  481. var dialer common.Dialer
  482. // For HTTP, and when the meekConfig.DialAddress matches the
  483. // meekConfig.HostHeader, we let http.Transport handle proxying.
  484. // http.Transport will put the the HTTP server address in the HTTP
  485. // request line. In this one case, we can use an HTTP proxy that does
  486. // not offer CONNECT support.
  487. if strings.HasPrefix(dialConfig.UpstreamProxyURL, "http://") &&
  488. (meekConfig.DialAddress == meekConfig.HostHeader ||
  489. meekConfig.DialAddress == meekConfig.HostHeader+":80") {
  490. url, err := common.SafeParseURL(dialConfig.UpstreamProxyURL)
  491. if err != nil {
  492. return nil, errors.Trace(err)
  493. }
  494. proxyUrl = http.ProxyURL(url)
  495. // Here, the dialer must use the address that http.Transport
  496. // passes in (which will be proxy address).
  497. copyDialConfig := new(DialConfig)
  498. *copyDialConfig = *dialConfig
  499. copyDialConfig.UpstreamProxyURL = ""
  500. dialer = NewTCPDialer(copyDialConfig)
  501. // In this proxy case, the destination server address is in the
  502. // request line URL. net/http will render the request line using
  503. // the URL but preferring the Host header for the host value,
  504. // which means any custom host header will clobber the true
  505. // destination address. The URL.Opaque logic is applied in this
  506. // case, to force the request line URL value.
  507. //
  508. // This URL.Opaque setting assumes MeekModeRelay, with no path; at
  509. // this time plain HTTP is used only with MeekModeRelay.
  510. // x/net/http2 will reject requests where the URL.Opaque contains
  511. // more than the path; but HTTP/2 is not used in this case.
  512. values := dialConfig.CustomHeaders["Host"]
  513. if len(values) > 0 {
  514. opaqueURL = "http://" + meekConfig.DialAddress + "/"
  515. }
  516. } else {
  517. // If dialConfig.UpstreamProxyURL is set, HTTP proxying via
  518. // CONNECT will be used by the dialer.
  519. baseDialer := NewTCPDialer(dialConfig)
  520. // The dialer ignores any address that http.Transport will pass in
  521. // (derived from the HTTP request URL) and always dials
  522. // meekConfig.DialAddress.
  523. dialer = func(ctx context.Context, network, _ string) (net.Conn, error) {
  524. return baseDialer(ctx, network, meekConfig.DialAddress)
  525. }
  526. }
  527. if protocol.TunnelProtocolUsesMeekHTTP(meekConfig.ClientTunnelProtocol) {
  528. // Only apply transformer if it will perform a transform; otherwise
  529. // applying a no-op transform will incur an unnecessary performance
  530. // cost.
  531. if meekConfig.HTTPTransformerParameters != nil &&
  532. meekConfig.HTTPTransformerParameters.ProtocolTransformSpec != nil {
  533. dialer = transforms.WrapDialerWithHTTPTransformer(
  534. dialer, meekConfig.HTTPTransformerParameters)
  535. }
  536. }
  537. meek.connManager = newMeekUnderlyingConnManager(nil, dialer, nil)
  538. httpTransport := &http.Transport{
  539. Proxy: proxyUrl,
  540. DialContext: meek.connManager.dial,
  541. }
  542. if proxyUrl != nil {
  543. // When http.Transport is handling proxying, wrap transport with a
  544. // transport that (a) adds custom headers; (b) can perform HTTP
  545. // proxy auth negotiation.
  546. var err error
  547. transport, err = upstreamproxy.NewProxyAuthTransport(
  548. httpTransport, dialConfig.CustomHeaders)
  549. if err != nil {
  550. return nil, errors.Trace(err)
  551. }
  552. } else {
  553. transport = httpTransport
  554. }
  555. }
  556. url := &url.URL{
  557. Scheme: scheme,
  558. Host: meekConfig.HostHeader,
  559. Path: "/",
  560. Opaque: opaqueURL,
  561. }
  562. if scheme == "http" && proxyUrl == nil {
  563. // Add custom headers to HTTP. This may be unproxied HTTP, or CONNECT
  564. // method proxied HTTP, which is handled implicitly by DialTCP (in the
  565. // latter case, the CONNECT request itself will also have custom
  566. // headers via upstreamproxy applied by the dialer).
  567. //
  568. // When proxyUrl != nil, proxying is handled by http.Transport and
  569. // custom headers are set in upstreamproxy.NewProxyAuthTransport, above.
  570. additionalHeaders = dialConfig.CustomHeaders
  571. } else {
  572. additionalHeaders = make(http.Header)
  573. // User-Agent is passed in via dialConfig.CustomHeaders. Always use
  574. // any User-Agent header, even when not using all custom headers.
  575. userAgent := dialConfig.CustomHeaders.Get("User-Agent")
  576. if userAgent != "" {
  577. additionalHeaders.Set("User-Agent", userAgent)
  578. }
  579. }
  580. if meekConfig.AddPsiphonFrontingHeader {
  581. host, _, err := net.SplitHostPort(meekConfig.DialAddress)
  582. if err != nil {
  583. return nil, errors.Trace(err)
  584. }
  585. additionalHeaders.Set("X-Psiphon-Fronting-Address", host)
  586. }
  587. if meekConfig.AdditionalHeaders != nil {
  588. for name, value := range meekConfig.AdditionalHeaders {
  589. if _, ok := additionalHeaders[name]; !ok {
  590. additionalHeaders[name] = value
  591. }
  592. }
  593. }
  594. meek.url = url
  595. meek.additionalHeaders = additionalHeaders
  596. meek.transport = transport
  597. // stopRunning and cachedTLSDialer will now be closed in meek.Close()
  598. cleanupStopRunning = false
  599. cleanupConns = false
  600. // Allocate relay resources, including buffers and running the relay
  601. // go routine, only when running in relay mode.
  602. if meek.mode == MeekModeRelay {
  603. // The main loop of a MeekConn is run in the relay() goroutine.
  604. // A MeekConn implements net.Conn concurrency semantics:
  605. // "Multiple goroutines may invoke methods on a Conn simultaneously."
  606. //
  607. // Read() calls and relay() are synchronized by exchanging control of a single
  608. // receiveBuffer (bytes.Buffer). This single buffer may be:
  609. // - in the emptyReceiveBuffer channel when it is available and empty;
  610. // - in the partialReadBuffer channel when it is available and contains data;
  611. // - in the fullReadBuffer channel when it is available and full of data;
  612. // - "checked out" by relay or Read when they are are writing to or reading from the
  613. // buffer, respectively.
  614. // relay() will obtain the buffer from either the empty or partial channel but block when
  615. // the buffer is full. Read will obtain the buffer from the partial or full channel when
  616. // there is data to read but block when the buffer is empty.
  617. // Write() calls and relay() are synchronized in a similar way, using a single
  618. // sendBuffer.
  619. p := meek.getCustomParameters()
  620. if p.Bool(parameters.MeekLimitBufferSizes) {
  621. meek.fullReceiveBufferLength = p.Int(parameters.MeekLimitedFullReceiveBufferLength)
  622. meek.readPayloadChunkLength = p.Int(parameters.MeekLimitedReadPayloadChunkLength)
  623. } else {
  624. meek.fullReceiveBufferLength = p.Int(parameters.MeekFullReceiveBufferLength)
  625. meek.readPayloadChunkLength = p.Int(parameters.MeekReadPayloadChunkLength)
  626. }
  627. meek.emptyReceiveBuffer = make(chan *bytes.Buffer, 1)
  628. meek.partialReceiveBuffer = make(chan *bytes.Buffer, 1)
  629. meek.fullReceiveBuffer = make(chan *bytes.Buffer, 1)
  630. meek.emptySendBuffer = make(chan *bytes.Buffer, 1)
  631. meek.partialSendBuffer = make(chan *bytes.Buffer, 1)
  632. meek.fullSendBuffer = make(chan *bytes.Buffer, 1)
  633. meek.emptyReceiveBuffer <- new(bytes.Buffer)
  634. meek.emptySendBuffer <- new(bytes.Buffer)
  635. meek.relayWaitGroup.Add(1)
  636. go meek.relay()
  637. } else if meek.mode == MeekModeObfuscatedRoundTrip {
  638. meek.meekCookieEncryptionPublicKey = meekConfig.MeekCookieEncryptionPublicKey
  639. meek.meekObfuscatedKey = meekConfig.MeekObfuscatedKey
  640. meek.meekObfuscatorPaddingSeed = meekConfig.MeekObfuscatorPaddingSeed
  641. meek.clientTunnelProtocol = meekConfig.ClientTunnelProtocol
  642. } else if meek.mode == MeekModePlaintextRoundTrip ||
  643. meek.mode == MeekModeWrappedPlaintextRoundTrip {
  644. // MeekModeRelay and MeekModeObfuscatedRoundTrip set the Host header
  645. // implicitly via meek.url; MeekMode[Wrapped]PlaintextRoundTrip does
  646. // not use meek.url; it uses the RoundTrip input request.URL instead.
  647. // So the Host header is set to meekConfig.HostHeader explicitly here.
  648. meek.additionalHeaders.Add("Host", meekConfig.HostHeader)
  649. }
  650. return meek, nil
  651. }
  652. type meekPacketConnDialer func(ctx context.Context) (net.PacketConn, *net.UDPAddr, error)
  653. // meekUnderlyingConnManager tracks the TCP/TLS and UDP connections underlying
  654. // the meek HTTP/HTTPS/QUIC transports. This tracking is used to:
  655. //
  656. // - Use the cached predial TLS conn created in DialMeek.
  657. // - Gather metrics from mechanisms enabled in the underlying conns, such as
  658. // the fragmentor, or inproxy.
  659. // - Fully close all underlying connections with the MeekConn is closed.
  660. type meekUnderlyingConnManager struct {
  661. mutex sync.Mutex
  662. cachedConn net.Conn
  663. firstConn net.Conn
  664. firstPacketConn net.PacketConn
  665. dialer common.Dialer
  666. managedConns *common.Conns[net.Conn]
  667. packetConnDialer meekPacketConnDialer
  668. managedPacketConns *common.Conns[net.PacketConn]
  669. }
  670. type meekUnderlyingConn struct {
  671. net.Conn
  672. connManager *meekUnderlyingConnManager
  673. }
  674. func (conn *meekUnderlyingConn) Close() error {
  675. conn.connManager.managedConns.Remove(conn)
  676. // Note: no trace error to preserve error type
  677. return conn.Conn.Close()
  678. }
  679. type meekUnderlyingPacketConn struct {
  680. net.PacketConn
  681. connManager *meekUnderlyingConnManager
  682. }
  683. func (packetConn *meekUnderlyingPacketConn) Close() error {
  684. packetConn.connManager.managedPacketConns.Remove(packetConn)
  685. return packetConn.PacketConn.Close()
  686. }
  687. func newMeekUnderlyingConnManager(
  688. cachedConn net.Conn,
  689. dialer common.Dialer,
  690. packetConnDialer meekPacketConnDialer) *meekUnderlyingConnManager {
  691. m := &meekUnderlyingConnManager{
  692. dialer: dialer,
  693. managedConns: common.NewConns[net.Conn](),
  694. packetConnDialer: packetConnDialer,
  695. managedPacketConns: common.NewConns[net.PacketConn](),
  696. }
  697. if cachedConn != nil {
  698. m.cachedConn = &meekUnderlyingConn{Conn: cachedConn, connManager: m}
  699. m.firstConn = cachedConn
  700. }
  701. return m
  702. }
  703. func (m *meekUnderlyingConnManager) GetMetrics() common.LogFields {
  704. logFields := common.LogFields{}
  705. m.mutex.Lock()
  706. underlyingMetrics, ok := m.firstConn.(common.MetricsSource)
  707. if ok {
  708. logFields.Add(underlyingMetrics.GetMetrics())
  709. }
  710. underlyingMetrics, ok = m.firstPacketConn.(common.MetricsSource)
  711. if ok {
  712. logFields.Add(underlyingMetrics.GetMetrics())
  713. }
  714. m.mutex.Unlock()
  715. return logFields
  716. }
  717. func (m *meekUnderlyingConnManager) dial(
  718. ctx context.Context, network, addr string) (net.Conn, error) {
  719. if m.managedConns.IsClosed() {
  720. return nil, errors.TraceNew("closed")
  721. }
  722. // Consume the cached conn when present.
  723. m.mutex.Lock()
  724. var conn net.Conn
  725. if m.cachedConn != nil {
  726. conn = m.cachedConn
  727. m.cachedConn = nil
  728. }
  729. m.mutex.Unlock()
  730. if conn != nil {
  731. return conn, nil
  732. }
  733. // The mutex lock is not held for the duration of dial, allowing for
  734. // concurrent dials.
  735. conn, err := m.dialer(ctx, network, addr)
  736. if err != nil {
  737. // Note: no trace error to preserve error type
  738. return nil, err
  739. }
  740. // Keep a reference to the first underlying conn to be used as a
  741. // common.MetricsSource in GetMetrics. This enables capturing metrics
  742. // such as fragmentor configuration.
  743. m.mutex.Lock()
  744. if m.firstConn == nil {
  745. m.firstConn = conn
  746. }
  747. m.mutex.Unlock()
  748. // Wrap the dialed conn with meekUnderlyingConn, which will remove the
  749. // conn from the set of tracked conns when the conn is closed.
  750. conn = &meekUnderlyingConn{Conn: conn, connManager: m}
  751. if !m.managedConns.Add(conn) {
  752. _ = conn.Close()
  753. return nil, errors.TraceNew("closed")
  754. }
  755. return conn, nil
  756. }
  757. func (m *meekUnderlyingConnManager) dialPacketConn(
  758. ctx context.Context) (net.PacketConn, *net.UDPAddr, error) {
  759. if m.managedPacketConns.IsClosed() {
  760. return nil, nil, errors.TraceNew("closed")
  761. }
  762. packetConn, addr, err := m.packetConnDialer(ctx)
  763. if err != nil {
  764. // Note: no trace error to preserve error type
  765. return nil, nil, err
  766. }
  767. m.mutex.Lock()
  768. if m.firstPacketConn != nil {
  769. m.firstPacketConn = packetConn
  770. }
  771. m.mutex.Unlock()
  772. packetConn = &meekUnderlyingPacketConn{PacketConn: packetConn, connManager: m}
  773. if !m.managedPacketConns.Add(packetConn) {
  774. _ = packetConn.Close()
  775. return nil, nil, errors.TraceNew("closed")
  776. }
  777. return packetConn, addr, nil
  778. }
  779. func (m *meekUnderlyingConnManager) closeAll() {
  780. m.managedConns.CloseAll()
  781. m.managedPacketConns.CloseAll()
  782. }
  783. // Close terminates the meek connection and releases its resources. In in
  784. // MeekModeRelay, Close waits for the relay goroutine to stop.
  785. func (meek *MeekConn) Close() (err error) {
  786. // A mutex is required to support net.Conn concurrency semantics.
  787. meek.mutex.Lock()
  788. isClosed := meek.isClosed
  789. meek.isClosed = true
  790. meek.mutex.Unlock()
  791. if !isClosed {
  792. meek.stopRunning()
  793. meek.connManager.closeAll()
  794. meek.relayWaitGroup.Wait()
  795. // meek.transport.CloseIdleConnections is no longed called here since
  796. // meekUnderlyingConnManager.closeAll will terminate all underlying
  797. // connections and prevent opening any new connections.
  798. }
  799. return nil
  800. }
  801. // IsClosed implements the Closer interface. The return value
  802. // indicates whether the MeekConn has been closed.
  803. func (meek *MeekConn) IsClosed() bool {
  804. meek.mutex.Lock()
  805. isClosed := meek.isClosed
  806. meek.mutex.Unlock()
  807. return isClosed
  808. }
  809. // GetMetrics implements the common.MetricsSource interface.
  810. func (meek *MeekConn) GetMetrics() common.LogFields {
  811. logFields := make(common.LogFields)
  812. if meek.mode == MeekModeRelay {
  813. logFields["meek_cookie_size"] = meek.cookieSize
  814. logFields["meek_tls_padding"] = meek.tlsPadding
  815. logFields["meek_limit_request"] = meek.limitRequestPayloadLength
  816. logFields["meek_redial_probability"] = meek.redialTLSProbability
  817. }
  818. // Include metrics, such as fragmentor metrics, from the _first_ underlying
  819. // dial conn. Properties of subsequent underlying dial conns are not reflected
  820. // in these metrics; we assume that the first dial conn, which most likely
  821. // transits the various protocol handshakes, is most significant.
  822. logFields.Add(meek.connManager.GetMetrics())
  823. return logFields
  824. }
  825. // GetNoticeMetrics implements the common.NoticeMetricsSource interface.
  826. func (meek *MeekConn) GetNoticeMetrics() common.LogFields {
  827. // These fields are logged only in notices, for diagnostics. The server
  828. // will log the same values, but derives them from HTTP headers, so they
  829. // don't need to be sent in the API request.
  830. logFields := make(common.LogFields)
  831. logFields["meek_cookie_name"] = meek.cookie.Name
  832. logFields["meek_content_type"] = meek.contentType
  833. return logFields
  834. }
  835. // ObfuscatedRoundTrip makes a request to the meek server and returns the
  836. // response. A new, obfuscated meek cookie is created for every request. The
  837. // specified end point is recorded in the cookie and is not exposed as
  838. // plaintext in the meek traffic. The caller is responsible for securing and
  839. // obfuscating the request body.
  840. //
  841. // If Close is called before or concurrent with ObfuscatedRoundTrip, or before
  842. // the response body is read, idle connections may be left open.
  843. func (meek *MeekConn) ObfuscatedRoundTrip(
  844. requestCtx context.Context, endPoint string, requestBody []byte) ([]byte, error) {
  845. if meek.mode != MeekModeObfuscatedRoundTrip {
  846. return nil, errors.TraceNew("operation unsupported")
  847. }
  848. cookie, contentType, _, _, _, err := makeMeekObfuscationValues(
  849. meek.getCustomParameters(),
  850. meek.meekCookieEncryptionPublicKey,
  851. meek.meekObfuscatedKey,
  852. meek.meekObfuscatorPaddingSeed,
  853. meek.clientTunnelProtocol,
  854. endPoint)
  855. if err != nil {
  856. return nil, errors.Trace(err)
  857. }
  858. request, err := meek.newRequest(
  859. requestCtx, cookie, contentType, bytes.NewReader(requestBody), 0)
  860. if err != nil {
  861. return nil, errors.Trace(err)
  862. }
  863. meek.scheduleQUICCloseIdle(request)
  864. response, err := meek.transport.RoundTrip(request)
  865. if err == nil {
  866. defer response.Body.Close()
  867. if response.StatusCode != http.StatusOK {
  868. err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
  869. }
  870. }
  871. if err != nil {
  872. return nil, errors.Trace(err)
  873. }
  874. responseBody, err := ioutil.ReadAll(response.Body)
  875. if err != nil {
  876. return nil, errors.Trace(err)
  877. }
  878. return responseBody, nil
  879. }
  880. // RoundTrip implements the http.RoundTripper interface. RoundTrip may only be
  881. // used when TLS and server certificate verification are configured. RoundTrip
  882. // does not implement any security or obfuscation at the HTTP layer.
  883. //
  884. // If Close is called before or concurrent with RoundTrip, or before the
  885. // response body is read, idle connections may be left open.
  886. func (meek *MeekConn) RoundTrip(request *http.Request) (*http.Response, error) {
  887. if meek.mode != MeekModePlaintextRoundTrip &&
  888. meek.mode != MeekModeWrappedPlaintextRoundTrip {
  889. return nil, errors.TraceNew("operation unsupported")
  890. }
  891. requestCtx := request.Context()
  892. // Clone the request to apply addtional headers without modifying the input.
  893. request = request.Clone(requestCtx)
  894. meek.addAdditionalHeaders(request)
  895. meek.scheduleQUICCloseIdle(request)
  896. response, err := meek.transport.RoundTrip(request)
  897. if err != nil {
  898. return nil, errors.Trace(err)
  899. }
  900. return response, nil
  901. }
  902. // Read reads data from the connection.
  903. // net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
  904. func (meek *MeekConn) Read(buffer []byte) (n int, err error) {
  905. if meek.mode != MeekModeRelay {
  906. return 0, errors.TraceNew("operation unsupported")
  907. }
  908. if meek.IsClosed() {
  909. return 0, errors.TraceNew("meek connection is closed")
  910. }
  911. // Block until there is received data to consume
  912. var receiveBuffer *bytes.Buffer
  913. select {
  914. case receiveBuffer = <-meek.partialReceiveBuffer:
  915. case receiveBuffer = <-meek.fullReceiveBuffer:
  916. case <-meek.runCtx.Done():
  917. return 0, errors.TraceNew("meek connection has closed")
  918. }
  919. n, err = receiveBuffer.Read(buffer)
  920. meek.replaceReceiveBuffer(receiveBuffer)
  921. return n, err
  922. }
  923. // Write writes data to the connection.
  924. // net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
  925. func (meek *MeekConn) Write(buffer []byte) (n int, err error) {
  926. if meek.mode != MeekModeRelay {
  927. return 0, errors.TraceNew("operation unsupported")
  928. }
  929. if meek.IsClosed() {
  930. return 0, errors.TraceNew("meek connection is closed")
  931. }
  932. // Repeats until all n bytes are written
  933. n = len(buffer)
  934. for len(buffer) > 0 {
  935. // Block until there is capacity in the send buffer
  936. var sendBuffer *bytes.Buffer
  937. select {
  938. case sendBuffer = <-meek.emptySendBuffer:
  939. case sendBuffer = <-meek.partialSendBuffer:
  940. case <-meek.runCtx.Done():
  941. return 0, errors.TraceNew("meek connection has closed")
  942. }
  943. writeLen := meek.limitRequestPayloadLength - sendBuffer.Len()
  944. if writeLen > 0 {
  945. if writeLen > len(buffer) {
  946. writeLen = len(buffer)
  947. }
  948. _, err = sendBuffer.Write(buffer[:writeLen])
  949. buffer = buffer[writeLen:]
  950. }
  951. meek.replaceSendBuffer(sendBuffer)
  952. }
  953. return n, err
  954. }
  955. // LocalAddr is a stub implementation of net.Conn.LocalAddr
  956. func (meek *MeekConn) LocalAddr() net.Addr {
  957. return nil
  958. }
  959. // RemoteAddr is a stub implementation of net.Conn.RemoteAddr
  960. func (meek *MeekConn) RemoteAddr() net.Addr {
  961. return nil
  962. }
  963. // SetDeadline is a stub implementation of net.Conn.SetDeadline
  964. func (meek *MeekConn) SetDeadline(t time.Time) error {
  965. return errors.TraceNew("not supported")
  966. }
  967. // SetReadDeadline is a stub implementation of net.Conn.SetReadDeadline
  968. func (meek *MeekConn) SetReadDeadline(t time.Time) error {
  969. return errors.TraceNew("not supported")
  970. }
  971. // SetWriteDeadline is a stub implementation of net.Conn.SetWriteDeadline
  972. func (meek *MeekConn) SetWriteDeadline(t time.Time) error {
  973. return errors.TraceNew("not supported")
  974. }
  975. func (meek *MeekConn) replaceReceiveBuffer(receiveBuffer *bytes.Buffer) {
  976. switch {
  977. case receiveBuffer.Len() == 0:
  978. meek.emptyReceiveBuffer <- receiveBuffer
  979. case receiveBuffer.Len() >= meek.fullReceiveBufferLength:
  980. meek.fullReceiveBuffer <- receiveBuffer
  981. default:
  982. meek.partialReceiveBuffer <- receiveBuffer
  983. }
  984. }
  985. func (meek *MeekConn) replaceSendBuffer(sendBuffer *bytes.Buffer) {
  986. switch {
  987. case sendBuffer.Len() == 0:
  988. meek.emptySendBuffer <- sendBuffer
  989. case sendBuffer.Len() >= meek.limitRequestPayloadLength:
  990. meek.fullSendBuffer <- sendBuffer
  991. default:
  992. meek.partialSendBuffer <- sendBuffer
  993. }
  994. }
  995. // relay sends and receives tunneled traffic (payload). An HTTP request is
  996. // triggered when data is in the write queue or at a polling interval.
  997. // There's a geometric increase, up to a maximum, in the polling interval when
  998. // no data is exchanged. Only one HTTP request is in flight at a time.
  999. func (meek *MeekConn) relay() {
  1000. // Note: meek.Close() calls here in relay() are made asynchronously
  1001. // (using goroutines) since Close() will wait on this WaitGroup.
  1002. defer meek.relayWaitGroup.Done()
  1003. p := meek.getCustomParameters()
  1004. interval := prng.JitterDuration(
  1005. p.Duration(parameters.MeekMinPollInterval),
  1006. p.Float(parameters.MeekMinPollIntervalJitter))
  1007. p.Close()
  1008. timeout := time.NewTimer(interval)
  1009. defer timeout.Stop()
  1010. for {
  1011. timeout.Reset(interval)
  1012. // Block until there is payload to send or it is time to poll
  1013. var sendBuffer *bytes.Buffer
  1014. select {
  1015. case sendBuffer = <-meek.partialSendBuffer:
  1016. case sendBuffer = <-meek.fullSendBuffer:
  1017. case <-timeout.C:
  1018. // In the polling case, send an empty payload
  1019. case <-meek.runCtx.Done():
  1020. // Drop through to second Done() check
  1021. }
  1022. // Check Done() again, to ensure it takes precedence
  1023. select {
  1024. case <-meek.runCtx.Done():
  1025. return
  1026. default:
  1027. }
  1028. sendPayloadSize := 0
  1029. if sendBuffer != nil {
  1030. sendPayloadSize = sendBuffer.Len()
  1031. }
  1032. // relayRoundTrip will replace sendBuffer (by calling replaceSendBuffer). This
  1033. // is a compromise to conserve memory. Using a second buffer here, we could
  1034. // copy sendBuffer and immediately replace it, unblocking meekConn.Write() and
  1035. // allowing more upstream payload to immediately enqueue. Instead, the request
  1036. // payload is read directly from sendBuffer, including retries. Only once the
  1037. // server has acknowledged the request payload is sendBuffer replaced. This
  1038. // still allows meekConn.Write() to unblock before the round trip response is
  1039. // read.
  1040. receivedPayloadSize, err := meek.relayRoundTrip(sendBuffer)
  1041. if err != nil {
  1042. select {
  1043. case <-meek.runCtx.Done():
  1044. // In this case, meek.relayRoundTrip encountered Done(). Exit without
  1045. // logging error.
  1046. return
  1047. default:
  1048. }
  1049. NoticeWarning("%s", errors.Trace(err))
  1050. go meek.Close()
  1051. return
  1052. }
  1053. // Periodically re-dial the underlying TLS/TCP connection
  1054. // (notwithstanding the parameter name, this also applies to TCP
  1055. // connections for HTTP protocols).
  1056. if prng.FlipWeightedCoin(meek.redialTLSProbability) {
  1057. meek.transport.CloseIdleConnections()
  1058. }
  1059. // Calculate polling interval. When data is received,
  1060. // immediately request more. Otherwise, schedule next
  1061. // poll with exponential back off. Jitter and coin
  1062. // flips are used to avoid trivial, static traffic
  1063. // timing patterns.
  1064. p := meek.getCustomParameters()
  1065. if receivedPayloadSize > 0 || sendPayloadSize > 0 {
  1066. interval = 0
  1067. } else if interval == 0 {
  1068. interval = prng.JitterDuration(
  1069. p.Duration(parameters.MeekMinPollInterval),
  1070. p.Float(parameters.MeekMinPollIntervalJitter))
  1071. } else {
  1072. if p.WeightedCoinFlip(parameters.MeekApplyPollIntervalMultiplierProbability) {
  1073. interval =
  1074. time.Duration(float64(interval) *
  1075. p.Float(parameters.MeekPollIntervalMultiplier))
  1076. }
  1077. interval = prng.JitterDuration(
  1078. interval,
  1079. p.Float(parameters.MeekPollIntervalJitter))
  1080. if interval >= p.Duration(parameters.MeekMaxPollInterval) {
  1081. interval = prng.JitterDuration(
  1082. p.Duration(parameters.MeekMaxPollInterval),
  1083. p.Float(parameters.MeekMaxPollIntervalJitter))
  1084. }
  1085. }
  1086. p.Close()
  1087. }
  1088. }
  1089. // readCloseSignaller is an io.ReadCloser wrapper for an io.Reader
  1090. // that is passed, as the request body, to http.Transport.RoundTrip.
  1091. // readCloseSignaller adds the AwaitClosed call, which is used
  1092. // to schedule recycling the buffer underlying the reader only after
  1093. // RoundTrip has called Close and will no longer use the buffer.
  1094. // See: https://golang.org/pkg/net/http/#RoundTripper
  1095. type readCloseSignaller struct {
  1096. context context.Context
  1097. reader io.Reader
  1098. closed chan struct{}
  1099. }
  1100. func NewReadCloseSignaller(
  1101. context context.Context,
  1102. reader io.Reader) *readCloseSignaller {
  1103. return &readCloseSignaller{
  1104. context: context,
  1105. reader: reader,
  1106. closed: make(chan struct{}, 1),
  1107. }
  1108. }
  1109. func (r *readCloseSignaller) Read(p []byte) (int, error) {
  1110. return r.reader.Read(p)
  1111. }
  1112. func (r *readCloseSignaller) Close() error {
  1113. select {
  1114. case r.closed <- struct{}{}:
  1115. default:
  1116. }
  1117. return nil
  1118. }
  1119. func (r *readCloseSignaller) AwaitClosed() bool {
  1120. select {
  1121. case <-r.context.Done():
  1122. case <-r.closed:
  1123. return true
  1124. }
  1125. return false
  1126. }
  1127. // newRequest performs common request setup for both MeekModeRelay and
  1128. // MeekModeObfuscatedRoundTrip.
  1129. //
  1130. // newRequest is not safe for concurrent calls due to its use of
  1131. // setRequestContext.
  1132. //
  1133. // The caller must call the returned cancelFunc.
  1134. func (meek *MeekConn) newRequest(
  1135. requestCtx context.Context,
  1136. cookie *http.Cookie,
  1137. contentType string,
  1138. body io.Reader,
  1139. contentLength int) (*http.Request, error) {
  1140. request, err := http.NewRequest("POST", meek.url.String(), body)
  1141. if err != nil {
  1142. return nil, errors.Trace(err)
  1143. }
  1144. request = request.WithContext(requestCtx)
  1145. // Content-Length may not be be set automatically due to the
  1146. // underlying type of requestBody.
  1147. if contentLength > 0 {
  1148. request.ContentLength = int64(contentLength)
  1149. }
  1150. meek.addAdditionalHeaders(request)
  1151. request.Header.Set("Content-Type", contentType)
  1152. if cookie == nil {
  1153. cookie = meek.cookie
  1154. }
  1155. request.AddCookie(cookie)
  1156. return request, nil
  1157. }
  1158. // Workaround for h2quic.RoundTripper context issue. See comment in
  1159. // MeekConn.Close.
  1160. func (meek *MeekConn) scheduleQUICCloseIdle(request *http.Request) {
  1161. requestCtx := request.Context()
  1162. if meek.isQUIC && requestCtx != context.Background() {
  1163. go func() {
  1164. <-requestCtx.Done()
  1165. meek.transport.CloseIdleConnections()
  1166. }()
  1167. }
  1168. }
  1169. // relayRoundTrip configures and makes the actual HTTP POST request
  1170. func (meek *MeekConn) relayRoundTrip(sendBuffer *bytes.Buffer) (int64, error) {
  1171. // Retries are made when the round trip fails. This adds resiliency
  1172. // to connection interruption and intermittent failures.
  1173. //
  1174. // At least one retry is always attempted, and retries continue
  1175. // while still within a brief deadline -- 5 seconds, currently the
  1176. // deadline for an actively probed SSH connection to timeout. There
  1177. // is a brief delay between retries, allowing for intermittent
  1178. // failure states to resolve.
  1179. //
  1180. // Failure may occur at various stages of the HTTP request:
  1181. //
  1182. // 1. Before the request begins. In this case, the entire request
  1183. // may be rerun.
  1184. //
  1185. // 2. While sending the request payload. In this case, the client
  1186. // must resend its request payload. The server will not have
  1187. // relayed its partially received request payload.
  1188. //
  1189. // 3. After sending the request payload but before receiving
  1190. // a response. The client cannot distinguish between case 2 and
  1191. // this case, case 3. The client resends its payload and the
  1192. // server detects this and skips relaying the request payload.
  1193. //
  1194. // 4. While reading the response payload. The client will omit its
  1195. // request payload when retrying, as the server has already
  1196. // acknowledged it. The client will also indicate to the server
  1197. // the amount of response payload already received, and the
  1198. // server will skip resending the indicated amount of response
  1199. // payload.
  1200. //
  1201. // Retries are indicated to the server by adding a Range header,
  1202. // which includes the response payload resend position.
  1203. defer func() {
  1204. // Ensure sendBuffer is replaced, even in error code paths.
  1205. if sendBuffer != nil {
  1206. sendBuffer.Truncate(0)
  1207. meek.replaceSendBuffer(sendBuffer)
  1208. }
  1209. }()
  1210. retries := uint(0)
  1211. p := meek.getCustomParameters()
  1212. retryDeadline := time.Now().Add(p.Duration(parameters.MeekRoundTripRetryDeadline))
  1213. retryDelay := p.Duration(parameters.MeekRoundTripRetryMinDelay)
  1214. retryMaxDelay := p.Duration(parameters.MeekRoundTripRetryMaxDelay)
  1215. retryMultiplier := p.Float(parameters.MeekRoundTripRetryMultiplier)
  1216. p.Close()
  1217. serverAcknowledgedRequestPayload := false
  1218. receivedPayloadSize := int64(0)
  1219. for try := 0; ; try++ {
  1220. // Omit the request payload when retrying after receiving a
  1221. // partial server response.
  1222. var signaller *readCloseSignaller
  1223. var requestBody io.ReadCloser
  1224. contentLength := 0
  1225. if !serverAcknowledgedRequestPayload && sendBuffer != nil {
  1226. // sendBuffer will be replaced once the data is no longer needed,
  1227. // when RoundTrip calls Close on the Body; this allows meekConn.Write()
  1228. // to unblock and start buffering data for the next roung trip while
  1229. // still reading the current round trip response. signaller provides
  1230. // the hook for awaiting RoundTrip's call to Close.
  1231. signaller = NewReadCloseSignaller(meek.runCtx, bytes.NewReader(sendBuffer.Bytes()))
  1232. requestBody = signaller
  1233. contentLength = sendBuffer.Len()
  1234. }
  1235. // - meek.stopRunning() will abort a round trip in flight
  1236. // - round trip will abort if it exceeds timeout
  1237. requestCtx, cancelFunc := context.WithTimeout(
  1238. meek.runCtx,
  1239. meek.getCustomParameters().Duration(parameters.MeekRoundTripTimeout))
  1240. defer cancelFunc()
  1241. request, err := meek.newRequest(
  1242. requestCtx,
  1243. nil,
  1244. meek.contentType,
  1245. requestBody,
  1246. contentLength)
  1247. if err != nil {
  1248. // Don't retry when can't initialize a Request
  1249. return 0, errors.Trace(err)
  1250. }
  1251. expectedStatusCode := http.StatusOK
  1252. // When retrying, add a Range header to indicate how much
  1253. // of the response was already received.
  1254. if try > 0 {
  1255. expectedStatusCode = http.StatusPartialContent
  1256. request.Header.Set("Range", fmt.Sprintf("bytes=%d-", receivedPayloadSize))
  1257. }
  1258. response, err := meek.transport.RoundTrip(request)
  1259. // Wait for RoundTrip to call Close on the request body, when
  1260. // there is one. This is necessary to ensure it's safe to
  1261. // subsequently replace sendBuffer in both the success and
  1262. // error cases.
  1263. if signaller != nil {
  1264. if !signaller.AwaitClosed() {
  1265. // AwaitClosed encountered Done(). Abort immediately. Do not
  1266. // replace sendBuffer, as we cannot be certain RoundTrip is
  1267. // done with it. MeekConn.Write will exit on Done and not hang
  1268. // awaiting sendBuffer.
  1269. sendBuffer = nil
  1270. return 0, errors.TraceNew("meek connection has closed")
  1271. }
  1272. }
  1273. if err != nil {
  1274. select {
  1275. case <-meek.runCtx.Done():
  1276. // Exit without retrying and without logging error.
  1277. return 0, errors.Trace(err)
  1278. default:
  1279. }
  1280. NoticeWarning("meek round trip failed: %s", err)
  1281. // ...continue to retry
  1282. }
  1283. if err == nil {
  1284. if response.StatusCode != expectedStatusCode &&
  1285. // Certain http servers return 200 OK where we expect 206, so accept that.
  1286. !(expectedStatusCode == http.StatusPartialContent && response.StatusCode == http.StatusOK) {
  1287. // Don't retry when the status code is incorrect
  1288. response.Body.Close()
  1289. return 0, errors.Tracef(
  1290. "unexpected status code: %d instead of %d",
  1291. response.StatusCode, expectedStatusCode)
  1292. }
  1293. // Update meek session cookie
  1294. for _, c := range response.Cookies() {
  1295. if meek.cookie.Name == c.Name {
  1296. meek.cookie.Value = c.Value
  1297. break
  1298. }
  1299. }
  1300. // Received the response status code, so the server
  1301. // must have received the request payload.
  1302. serverAcknowledgedRequestPayload = true
  1303. // sendBuffer is now no longer required for retries, and the
  1304. // buffer may be replaced; this allows meekConn.Write() to unblock
  1305. // and start buffering data for the next round trip while still
  1306. // reading the current round trip response.
  1307. if sendBuffer != nil {
  1308. // Assumes signaller.AwaitClosed is called above, so
  1309. // sendBuffer will no longer be accessed by RoundTrip.
  1310. sendBuffer.Truncate(0)
  1311. meek.replaceSendBuffer(sendBuffer)
  1312. sendBuffer = nil
  1313. }
  1314. readPayloadSize, err := meek.readPayload(response.Body)
  1315. response.Body.Close()
  1316. // receivedPayloadSize is the number of response
  1317. // payload bytes received and relayed. A retry can
  1318. // resume after this position.
  1319. receivedPayloadSize += readPayloadSize
  1320. if err != nil {
  1321. NoticeWarning("meek read payload failed: %s", err)
  1322. // ...continue to retry
  1323. } else {
  1324. // Round trip completed successfully
  1325. break
  1326. }
  1327. }
  1328. // Release context resources immediately.
  1329. cancelFunc()
  1330. // Either the request failed entirely, or there was a failure
  1331. // streaming the response payload. Always retry once. Then
  1332. // retry if time remains; when the next delay exceeds the time
  1333. // remaining until the deadline, do not retry.
  1334. now := time.Now()
  1335. if retries >= 1 &&
  1336. (now.After(retryDeadline) || retryDeadline.Sub(now) <= retryDelay) {
  1337. return 0, errors.Trace(err)
  1338. }
  1339. retries += 1
  1340. delayTimer := time.NewTimer(retryDelay)
  1341. select {
  1342. case <-delayTimer.C:
  1343. case <-meek.runCtx.Done():
  1344. delayTimer.Stop()
  1345. return 0, errors.Trace(err)
  1346. }
  1347. // Increase the next delay, to back off and avoid excessive
  1348. // activity in conditions such as no network connectivity.
  1349. retryDelay = time.Duration(
  1350. float64(retryDelay) * retryMultiplier)
  1351. if retryDelay >= retryMaxDelay {
  1352. retryDelay = retryMaxDelay
  1353. }
  1354. }
  1355. return receivedPayloadSize, nil
  1356. }
  1357. // Add additional headers to the HTTP request using the same method we use for adding
  1358. // custom headers to HTTP proxy requests.
  1359. func (meek *MeekConn) addAdditionalHeaders(request *http.Request) {
  1360. for name, value := range meek.additionalHeaders {
  1361. if name == "Host" {
  1362. if len(value) > 0 {
  1363. request.Host = value[0]
  1364. }
  1365. } else {
  1366. request.Header[name] = value
  1367. }
  1368. }
  1369. }
  1370. // readPayload reads the HTTP response in chunks, making the read buffer available
  1371. // to MeekConn.Read() calls after each chunk; the intention is to allow bytes to
  1372. // flow back to the reader as soon as possible instead of buffering the entire payload.
  1373. //
  1374. // When readPayload returns an error, the totalSize output is remains valid -- it's the
  1375. // number of payload bytes successfully read and relayed.
  1376. func (meek *MeekConn) readPayload(
  1377. receivedPayload io.ReadCloser) (totalSize int64, err error) {
  1378. defer receivedPayload.Close()
  1379. totalSize = 0
  1380. for {
  1381. reader := io.LimitReader(receivedPayload, int64(meek.readPayloadChunkLength))
  1382. // Block until there is capacity in the receive buffer
  1383. var receiveBuffer *bytes.Buffer
  1384. select {
  1385. case receiveBuffer = <-meek.emptyReceiveBuffer:
  1386. case receiveBuffer = <-meek.partialReceiveBuffer:
  1387. case <-meek.runCtx.Done():
  1388. return 0, nil
  1389. }
  1390. // Note: receiveBuffer size may exceed meek.fullReceiveBufferLength by up to the size
  1391. // of one received payload. The meek.fullReceiveBufferLength value is just a guideline.
  1392. n, err := receiveBuffer.ReadFrom(reader)
  1393. meek.replaceReceiveBuffer(receiveBuffer)
  1394. totalSize += n
  1395. if err != nil {
  1396. return totalSize, errors.Trace(err)
  1397. }
  1398. if n == 0 {
  1399. break
  1400. }
  1401. }
  1402. return totalSize, nil
  1403. }
  1404. // makeMeekObfuscationValues creates the meek cookie, to be sent with initial
  1405. // meek HTTP request, and other meek obfuscation values. The cookies contains
  1406. // obfuscated metadata, including meek version and other protocol information.
  1407. //
  1408. // In round tripper mode, the cookie contains the destination endpoint for the
  1409. // round trip request.
  1410. //
  1411. // In relay mode, the server will create a session using the cookie values and
  1412. // send the session ID back to the client via Set-Cookie header. The client
  1413. // must use that value with all consequent HTTP requests.
  1414. //
  1415. // In plain HTTP meek protocols, the cookie is visible over the adversary
  1416. // network, so the cookie is encrypted and obfuscated.
  1417. //
  1418. // Obsolete meek cookie fields used by the legacy server stack are no longer
  1419. // sent. These include ServerAddress and SessionID.
  1420. //
  1421. // The request payload limit and TLS redial probability apply only to relay
  1422. // mode and are selected once and used for the duration of a meek connction.
  1423. func makeMeekObfuscationValues(
  1424. p parameters.ParametersAccessor,
  1425. meekCookieEncryptionPublicKey string,
  1426. meekObfuscatedKey string,
  1427. meekObfuscatorPaddingPRNGSeed *prng.Seed,
  1428. clientTunnelProtocol string,
  1429. endPoint string,
  1430. ) (cookie *http.Cookie,
  1431. contentType string,
  1432. tlsPadding int,
  1433. limitRequestPayloadLength int,
  1434. redialTLSProbability float64,
  1435. err error) {
  1436. if meekCookieEncryptionPublicKey == "" {
  1437. return nil, "", 0, 0, 0.0, errors.TraceNew("missing public key")
  1438. }
  1439. cookieData := &protocol.MeekCookieData{
  1440. MeekProtocolVersion: MEEK_PROTOCOL_VERSION,
  1441. ClientTunnelProtocol: clientTunnelProtocol,
  1442. EndPoint: endPoint,
  1443. }
  1444. serializedCookie, err := json.Marshal(cookieData)
  1445. if err != nil {
  1446. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1447. }
  1448. // Encrypt the JSON data
  1449. // NaCl box is used for encryption. The peer public key comes from the server entry.
  1450. // Nonce is always all zeros, and is not sent in the cookie (the server also uses an all-zero nonce).
  1451. // http://nacl.cace-project.eu/box.html:
  1452. // "There is no harm in having the same nonce for different messages if the {sender, receiver} sets are
  1453. // different. This is true even if the sets overlap. For example, a sender can use the same nonce for two
  1454. // different messages if the messages are sent to two different public keys."
  1455. var nonce [24]byte
  1456. var publicKey [32]byte
  1457. decodedPublicKey, err := base64.StdEncoding.DecodeString(meekCookieEncryptionPublicKey)
  1458. if err != nil {
  1459. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1460. }
  1461. copy(publicKey[:], decodedPublicKey)
  1462. ephemeralPublicKey, ephemeralPrivateKey, err := box.GenerateKey(rand.Reader)
  1463. if err != nil {
  1464. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1465. }
  1466. box := box.Seal(nil, serializedCookie, &nonce, &publicKey, ephemeralPrivateKey)
  1467. encryptedCookie := make([]byte, 32+len(box))
  1468. copy(encryptedCookie[0:32], ephemeralPublicKey[0:32])
  1469. copy(encryptedCookie[32:], box)
  1470. maxPadding := p.Int(parameters.MeekCookieMaxPadding)
  1471. // Obfuscate the encrypted data. NewClientObfuscator checks that
  1472. // meekObfuscatedKey isn't missing.
  1473. obfuscator, err := obfuscator.NewClientObfuscator(
  1474. &obfuscator.ObfuscatorConfig{
  1475. Keyword: meekObfuscatedKey,
  1476. PaddingPRNGSeed: meekObfuscatorPaddingPRNGSeed,
  1477. MaxPadding: &maxPadding})
  1478. if err != nil {
  1479. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1480. }
  1481. obfuscatedCookie, _ := obfuscator.SendPreamble()
  1482. seedLen := len(obfuscatedCookie)
  1483. obfuscatedCookie = append(obfuscatedCookie, encryptedCookie...)
  1484. obfuscator.ObfuscateClientToServer(obfuscatedCookie[seedLen:])
  1485. cookieNamePRNG, err := obfuscator.GetDerivedPRNG("meek-cookie-name")
  1486. if err != nil {
  1487. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1488. }
  1489. var cookieName string
  1490. if cookieNamePRNG.FlipWeightedCoin(p.Float(parameters.MeekAlternateCookieNameProbability)) {
  1491. cookieName = values.GetCookieName(cookieNamePRNG)
  1492. } else {
  1493. // Format the HTTP cookie
  1494. // The format is <random letter 'A'-'Z'>=<base64 data>, which is intended to match common cookie formats.
  1495. A := int('A')
  1496. Z := int('Z')
  1497. // letterIndex is integer in range [int('A'), int('Z')]
  1498. letterIndex := cookieNamePRNG.Intn(Z - A + 1)
  1499. cookieName = string(byte(A + letterIndex))
  1500. }
  1501. cookie = &http.Cookie{
  1502. Name: cookieName,
  1503. Value: base64.StdEncoding.EncodeToString(obfuscatedCookie)}
  1504. contentTypePRNG, err := obfuscator.GetDerivedPRNG("meek-content-type")
  1505. if err != nil {
  1506. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1507. }
  1508. if contentTypePRNG.FlipWeightedCoin(p.Float(parameters.MeekAlternateContentTypeProbability)) {
  1509. contentType = values.GetContentType(contentTypePRNG)
  1510. } else {
  1511. contentType = "application/octet-stream"
  1512. }
  1513. tlsPadding = 0
  1514. limitRequestPayloadLength = MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1515. redialTLSProbability = 0.0
  1516. tunnelProtocols := p.TunnelProtocols(parameters.MeekTrafficShapingLimitProtocols)
  1517. if (len(tunnelProtocols) == 0 ||
  1518. common.Contains(tunnelProtocols, clientTunnelProtocol)) &&
  1519. p.WeightedCoinFlip(parameters.MeekTrafficShapingProbability) {
  1520. limitRequestPayloadLengthPRNG, err := obfuscator.GetDerivedPRNG(
  1521. "meek-limit-request-payload-length")
  1522. if err != nil {
  1523. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1524. }
  1525. minLength := p.Int(parameters.MeekMinLimitRequestPayloadLength)
  1526. if minLength > MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1527. minLength = MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1528. }
  1529. maxLength := p.Int(parameters.MeekMaxLimitRequestPayloadLength)
  1530. if maxLength > MEEK_MAX_REQUEST_PAYLOAD_LENGTH {
  1531. maxLength = MEEK_MAX_REQUEST_PAYLOAD_LENGTH
  1532. }
  1533. limitRequestPayloadLength = limitRequestPayloadLengthPRNG.Range(
  1534. minLength, maxLength)
  1535. minPadding := p.Int(parameters.MeekMinTLSPadding)
  1536. maxPadding := p.Int(parameters.MeekMaxTLSPadding)
  1537. // Maximum padding size per RFC 7685
  1538. if maxPadding > 65535 {
  1539. maxPadding = 65535
  1540. }
  1541. if maxPadding > 0 {
  1542. tlsPaddingPRNG, err := obfuscator.GetDerivedPRNG(
  1543. "meek-tls-padding")
  1544. if err != nil {
  1545. return nil, "", 0, 0, 0.0, errors.Trace(err)
  1546. }
  1547. tlsPadding = tlsPaddingPRNG.Range(minPadding, maxPadding)
  1548. }
  1549. redialTLSProbability = p.Float(parameters.MeekRedialTLSProbability)
  1550. }
  1551. return cookie, contentType, tlsPadding, limitRequestPayloadLength, redialTLSProbability, nil
  1552. }