meekConn.go 59 KB

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