meekConn.go 58 KB

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