meekConn.go 60 KB

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