meekConn.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. golangtls "crypto/tls"
  25. "encoding/base64"
  26. "encoding/json"
  27. "errors"
  28. "fmt"
  29. "io"
  30. "net"
  31. "net/http"
  32. "net/url"
  33. "strings"
  34. "sync"
  35. "sync/atomic"
  36. "time"
  37. "github.com/Psiphon-Inc/goarista/monotime"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/box"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tls"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
  43. "golang.org/x/net/http2"
  44. )
  45. // MeekConn is based on meek-client.go from Tor and Psiphon:
  46. //
  47. // https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
  48. // CC0 1.0 Universal
  49. //
  50. // https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
  51. const (
  52. MEEK_PROTOCOL_VERSION = 3
  53. MEEK_COOKIE_MAX_PADDING = 32
  54. MAX_SEND_PAYLOAD_LENGTH = 65536
  55. FULL_RECEIVE_BUFFER_LENGTH = 4194304
  56. READ_PAYLOAD_CHUNK_LENGTH = 65536
  57. LIMITED_FULL_RECEIVE_BUFFER_LENGTH = 131072
  58. LIMITED_READ_PAYLOAD_CHUNK_LENGTH = 4096
  59. MIN_POLL_INTERVAL = 100 * time.Millisecond
  60. MIN_POLL_INTERVAL_JITTER = 0.3
  61. MAX_POLL_INTERVAL = 5 * time.Second
  62. MAX_POLL_INTERVAL_JITTER = 0.1
  63. POLL_INTERVAL_MULTIPLIER = 1.5
  64. POLL_INTERVAL_JITTER = 0.1
  65. MEEK_ROUND_TRIP_RETRY_DEADLINE = 5 * time.Second
  66. MEEK_ROUND_TRIP_RETRY_MIN_DELAY = 50 * time.Millisecond
  67. MEEK_ROUND_TRIP_RETRY_MAX_DELAY = 1000 * time.Millisecond
  68. MEEK_ROUND_TRIP_RETRY_MULTIPLIER = 2
  69. MEEK_ROUND_TRIP_TIMEOUT = 20 * time.Second
  70. )
  71. // MeekConfig specifies the behavior of a MeekConn
  72. type MeekConfig struct {
  73. // LimitBufferSizes indicates whether to use smaller buffers to
  74. // conserve memory.
  75. LimitBufferSizes bool
  76. // DialAddress is the actual network address to dial to establish a
  77. // connection to the meek server. This may be either a fronted or
  78. // direct address. The address must be in the form "host:port",
  79. // where host may be a domain name or IP address.
  80. DialAddress string
  81. // UseHTTPS indicates whether to use HTTPS (true) or HTTP (false).
  82. UseHTTPS bool
  83. // TLSProfile specifies the TLS profile to use for all underlying
  84. // TLS connections created by this meek connection. Valid values
  85. // are the possible values for CustomTLSConfig.TLSProfile.
  86. // TLSProfile will be used only when DialConfig.UseIndistinguishableTLS
  87. // is set in the DialConfig passed in to DialMeek.
  88. TLSProfile string
  89. // UseObfuscatedSessionTickets indicates whether to use obfuscated
  90. // session tickets. Assumes UseHTTPS is true.
  91. UseObfuscatedSessionTickets bool
  92. // SNIServerName is the value to place in the TLS SNI server_name
  93. // field when HTTPS is used.
  94. SNIServerName string
  95. // HostHeader is the value to place in the HTTP request Host header.
  96. HostHeader string
  97. // TransformedHostName records whether a hostname transformation is
  98. // in effect. This value is used for stats reporting.
  99. TransformedHostName bool
  100. // ClientTunnelProtocol is the protocol the client is using. It's
  101. // included in the meek cookie for optional use by the server, in
  102. // cases where the server cannot unambiguously determine the
  103. // tunnel protocol.
  104. ClientTunnelProtocol string
  105. // The following values are used to create the obfuscated meek cookie.
  106. PsiphonServerAddress string
  107. SessionID string
  108. MeekCookieEncryptionPublicKey string
  109. MeekObfuscatedKey string
  110. }
  111. // MeekConn is a network connection that tunnels TCP over HTTP and supports "fronting". Meek sends
  112. // client->server flow in HTTP request bodies and receives server->client flow in HTTP response bodies.
  113. // Polling is used to achieve full duplex TCP.
  114. //
  115. // Fronting is an obfuscation technique in which the connection
  116. // to a web server, typically a CDN, is indistinguishable from any other HTTPS connection to the generic
  117. // "fronting domain" -- the HTTP Host header is used to route the requests to the actual destination.
  118. // See https://trac.torproject.org/projects/tor/wiki/doc/meek for more details.
  119. //
  120. // MeekConn also operates in unfronted mode, in which plain HTTP connections are made without routing
  121. // through a CDN.
  122. type MeekConn struct {
  123. url *url.URL
  124. additionalHeaders http.Header
  125. cookie *http.Cookie
  126. pendingConns *common.Conns
  127. cachedTLSDialer *cachedTLSDialer
  128. transport transporter
  129. mutex sync.Mutex
  130. isClosed bool
  131. runContext context.Context
  132. stopRunning context.CancelFunc
  133. relayWaitGroup *sync.WaitGroup
  134. fullReceiveBufferLength int
  135. readPayloadChunkLength int
  136. emptyReceiveBuffer chan *bytes.Buffer
  137. partialReceiveBuffer chan *bytes.Buffer
  138. fullReceiveBuffer chan *bytes.Buffer
  139. emptySendBuffer chan *bytes.Buffer
  140. partialSendBuffer chan *bytes.Buffer
  141. fullSendBuffer chan *bytes.Buffer
  142. }
  143. // transporter is implemented by both http.Transport and upstreamproxy.ProxyAuthTransport.
  144. type transporter interface {
  145. CloseIdleConnections()
  146. RoundTrip(req *http.Request) (resp *http.Response, err error)
  147. }
  148. // DialMeek returns an initialized meek connection. A meek connection is
  149. // an HTTP session which does not depend on an underlying socket connection (although
  150. // persistent HTTP connections are used for performance). This function does not
  151. // wait for the connection to be "established" before returning. A goroutine
  152. // is spawned which will eventually start HTTP polling.
  153. // When frontingAddress is not "", fronting is used. This option assumes caller has
  154. // already checked server entry capabilities.
  155. func DialMeek(
  156. meekConfig *MeekConfig,
  157. dialConfig *DialConfig) (meek *MeekConn, err error) {
  158. // Configure transport
  159. // Note: MeekConn has its own PendingConns to manage the underlying HTTP transport connections,
  160. // which may be interrupted on MeekConn.Close(). This code previously used the establishTunnel
  161. // pendingConns here, but that was a lifecycle mismatch: we don't want to abort HTTP transport
  162. // connections while MeekConn is still in use.
  163. pendingConns := new(common.Conns)
  164. // Use a copy of DialConfig with the meek pendingConns
  165. meekDialConfig := new(DialConfig)
  166. *meekDialConfig = *dialConfig
  167. meekDialConfig.PendingConns = pendingConns
  168. var scheme string
  169. cleanupCachedTLSDialer := true
  170. var cachedTLSDialer *cachedTLSDialer
  171. var transport transporter
  172. var additionalHeaders http.Header
  173. var proxyUrl func(*http.Request) (*url.URL, error)
  174. // Close any cached pre-dialed conn in error cases
  175. defer func() {
  176. if cleanupCachedTLSDialer && cachedTLSDialer != nil {
  177. cachedTLSDialer.Close()
  178. }
  179. }()
  180. if meekConfig.UseHTTPS {
  181. // Custom TLS dialer:
  182. //
  183. // 1. ignores the HTTP request address and uses the fronting domain
  184. // 2. optionally disables SNI -- SNI breaks fronting when used with certain CDNs.
  185. // 3. skips verifying the server cert.
  186. //
  187. // Reasoning for #3:
  188. //
  189. // With a TLS MiM attack in place, and server certs verified, we'll fail to connect because the client
  190. // will refuse to connect. That's not a successful outcome.
  191. //
  192. // With a MiM attack in place, and server certs not verified, we'll fail to connect if the MiM is actively
  193. // targeting Psiphon and classifying the HTTP traffic by Host header or payload signature.
  194. //
  195. // However, in the case of a passive MiM that's just recording traffic or an active MiM that's targeting
  196. // something other than Psiphon, the client will connect. This is a successful outcome.
  197. //
  198. // What is exposed to the MiM? The Host header does not contain a Psiphon server IP address, just an
  199. // unrelated, randomly generated domain name which cannot be used to block direct connections. The
  200. // Psiphon server IP is sent over meek, but it's in the encrypted cookie.
  201. //
  202. // The payload (user traffic) gets its confidentiality and integrity from the underlying SSH protocol.
  203. // So, nothing is leaked to the MiM apart from signatures which could be used to classify the traffic
  204. // as Psiphon to possibly block it; but note that not revealing that the client is Psiphon is outside
  205. // our threat model; we merely seek to evade mass blocking by taking steps that require progressively
  206. // more effort to block.
  207. //
  208. // There is a subtle attack remaining: an adversary that can MiM some CDNs but not others (and so can
  209. // classify Psiphon traffic on some CDNs but not others) may throttle non-MiM CDNs so that our server
  210. // selection always chooses tunnels to the MiM CDN (without any server cert verification, we won't
  211. // exclusively connect to non-MiM CDNs); then the adversary kills the underlying TCP connection after
  212. // some short period. This is mitigated by the "impaired" protocol classification mechanism.
  213. scheme = "https"
  214. tlsConfig := &CustomTLSConfig{
  215. DialAddr: meekConfig.DialAddress,
  216. Dial: NewTCPDialer(meekDialConfig),
  217. Timeout: meekDialConfig.ConnectTimeout,
  218. SNIServerName: meekConfig.SNIServerName,
  219. SkipVerify: true,
  220. UseIndistinguishableTLS: meekDialConfig.UseIndistinguishableTLS,
  221. TLSProfile: meekConfig.TLSProfile,
  222. TrustedCACertificatesFilename: meekDialConfig.TrustedCACertificatesFilename,
  223. }
  224. if meekConfig.UseObfuscatedSessionTickets {
  225. tlsConfig.ObfuscatedSessionTicketKey = meekConfig.MeekObfuscatedKey
  226. }
  227. tlsDialer := NewCustomTLSDialer(tlsConfig)
  228. // Pre-dial one TLS connection in order to inspect the negotiated
  229. // application protocol. Then we create an HTTP/2 or HTTP/1.1 transport
  230. // depending on which protocol was negotiated. The TLS dialer
  231. // is assumed to negotiate only "h2" or "http/1.1"; or not negotiate
  232. // an application protocol.
  233. //
  234. // We cannot rely on net/http's HTTP/2 support since it's only
  235. // activated when http.Transport.DialTLS returns a golang crypto/tls.Conn;
  236. // e.g., https://github.com/golang/go/blob/c8aec4095e089ff6ac50d18e97c3f46561f14f48/src/net/http/transport.go#L1040
  237. //
  238. // The pre-dialed connection is stored in a cachedTLSDialer, which will
  239. // return the cached pre-dialed connection to its first Dial caller, and
  240. // use the tlsDialer for all other Dials.
  241. //
  242. // cachedTLSDialer.Close() must be called on all exits paths from this
  243. // function and in meek.Close() to ensure the cached conn is closed in
  244. // any case where no Dial call is made.
  245. //
  246. // The pre-dial must be interruptible so that DialMeek doesn't block and
  247. // hang/delay a shutdown or end of establishment. So the pre-dial uses
  248. // the Controller's PendingConns, not the MeekConn PendingConns. For this
  249. // purpose, a special preDialer is configured.
  250. //
  251. // Only one pre-dial attempt is made; there are no retries. This differs
  252. // from roundTrip, which retries and may redial for each retry. Retries
  253. // at the pre-dial phase are less useful since there's no active session
  254. // to preserve, and establishment will simply try another server. Note
  255. // that the underlying TCPDial may still try multiple IP addreses when
  256. // the destination is a domain and ir resolves to multiple IP adresses.
  257. preConfig := &CustomTLSConfig{}
  258. *preConfig = *tlsConfig
  259. preConfig.Dial = NewTCPDialer(dialConfig)
  260. preDialer := NewCustomTLSDialer(preConfig)
  261. // As DialAddr is set in the CustomTLSConfig, no address is required here.
  262. preConn, err := preDialer("tcp", "")
  263. if err != nil {
  264. return nil, common.ContextError(err)
  265. }
  266. // Cancel interruptibility to keep this connection alive after establishment.
  267. dialConfig.PendingConns.Remove(preConn)
  268. isHTTP2 := false
  269. if tlsConn, ok := preConn.(*tls.Conn); ok {
  270. state := tlsConn.ConnectionState()
  271. if state.NegotiatedProtocolIsMutual &&
  272. state.NegotiatedProtocol == "h2" {
  273. isHTTP2 = true
  274. }
  275. }
  276. cachedTLSDialer = NewCachedTLSDialer(preConn, tlsDialer)
  277. if isHTTP2 {
  278. NoticeInfo("negotiated HTTP/2 for %s", meekConfig.DialAddress)
  279. transport = &http2.Transport{
  280. DialTLS: func(network, addr string, _ *golangtls.Config) (net.Conn, error) {
  281. return cachedTLSDialer.Dial(network, addr)
  282. },
  283. }
  284. } else {
  285. transport = &http.Transport{
  286. DialTLS: cachedTLSDialer.Dial,
  287. }
  288. }
  289. } else {
  290. scheme = "http"
  291. // The dialer ignores address that http.Transport will pass in (derived
  292. // from the HTTP request URL) and always dials meekConfig.DialAddress.
  293. dialer := func(string, string) (net.Conn, error) {
  294. return NewTCPDialer(meekDialConfig)("tcp", meekConfig.DialAddress)
  295. }
  296. // For HTTP, and when the meekConfig.DialAddress matches the
  297. // meekConfig.HostHeader, we let http.Transport handle proxying.
  298. // http.Transport will put the the HTTP server address in the HTTP
  299. // request line. In this one case, we can use an HTTP proxy that does
  300. // not offer CONNECT support.
  301. if strings.HasPrefix(meekDialConfig.UpstreamProxyUrl, "http://") &&
  302. (meekConfig.DialAddress == meekConfig.HostHeader ||
  303. meekConfig.DialAddress == meekConfig.HostHeader+":80") {
  304. url, err := url.Parse(meekDialConfig.UpstreamProxyUrl)
  305. if err != nil {
  306. return nil, common.ContextError(err)
  307. }
  308. proxyUrl = http.ProxyURL(url)
  309. meekDialConfig.UpstreamProxyUrl = ""
  310. // Here, the dialer must use the address that http.Transport
  311. // passes in (which will be proxy address).
  312. dialer = NewTCPDialer(meekDialConfig)
  313. }
  314. // TODO: wrap in an http.Client and use http.Client.Timeout which actually covers round trip
  315. httpTransport := &http.Transport{
  316. Proxy: proxyUrl,
  317. Dial: dialer,
  318. }
  319. if proxyUrl != nil {
  320. // Wrap transport with a transport that can perform HTTP proxy auth negotiation
  321. transport, err = upstreamproxy.NewProxyAuthTransport(httpTransport, meekDialConfig.CustomHeaders)
  322. if err != nil {
  323. return nil, common.ContextError(err)
  324. }
  325. } else {
  326. transport = httpTransport
  327. }
  328. }
  329. url := &url.URL{
  330. Scheme: scheme,
  331. Host: meekConfig.HostHeader,
  332. Path: "/",
  333. }
  334. if meekConfig.UseHTTPS {
  335. host, _, err := net.SplitHostPort(meekConfig.DialAddress)
  336. if err != nil {
  337. return nil, common.ContextError(err)
  338. }
  339. additionalHeaders = map[string][]string{
  340. "X-Psiphon-Fronting-Address": {host},
  341. }
  342. } else {
  343. if proxyUrl == nil {
  344. additionalHeaders = meekDialConfig.CustomHeaders
  345. }
  346. }
  347. cookie, err := makeMeekCookie(meekConfig)
  348. if err != nil {
  349. return nil, common.ContextError(err)
  350. }
  351. runContext, stopRunning := context.WithCancel(context.Background())
  352. // The main loop of a MeekConn is run in the relay() goroutine.
  353. // A MeekConn implements net.Conn concurrency semantics:
  354. // "Multiple goroutines may invoke methods on a Conn simultaneously."
  355. //
  356. // Read() calls and relay() are synchronized by exchanging control of a single
  357. // receiveBuffer (bytes.Buffer). This single buffer may be:
  358. // - in the emptyReceiveBuffer channel when it is available and empty;
  359. // - in the partialReadBuffer channel when it is available and contains data;
  360. // - in the fullReadBuffer channel when it is available and full of data;
  361. // - "checked out" by relay or Read when they are are writing to or reading from the
  362. // buffer, respectively.
  363. // relay() will obtain the buffer from either the empty or partial channel but block when
  364. // the buffer is full. Read will obtain the buffer from the partial or full channel when
  365. // there is data to read but block when the buffer is empty.
  366. // Write() calls and relay() are synchronized in a similar way, using a single
  367. // sendBuffer.
  368. meek = &MeekConn{
  369. url: url,
  370. additionalHeaders: additionalHeaders,
  371. cookie: cookie,
  372. pendingConns: pendingConns,
  373. cachedTLSDialer: cachedTLSDialer,
  374. transport: transport,
  375. isClosed: false,
  376. runContext: runContext,
  377. stopRunning: stopRunning,
  378. relayWaitGroup: new(sync.WaitGroup),
  379. fullReceiveBufferLength: FULL_RECEIVE_BUFFER_LENGTH,
  380. readPayloadChunkLength: READ_PAYLOAD_CHUNK_LENGTH,
  381. emptyReceiveBuffer: make(chan *bytes.Buffer, 1),
  382. partialReceiveBuffer: make(chan *bytes.Buffer, 1),
  383. fullReceiveBuffer: make(chan *bytes.Buffer, 1),
  384. emptySendBuffer: make(chan *bytes.Buffer, 1),
  385. partialSendBuffer: make(chan *bytes.Buffer, 1),
  386. fullSendBuffer: make(chan *bytes.Buffer, 1),
  387. }
  388. // cachedTLSDialer will now be closed in meek.Close()
  389. cleanupCachedTLSDialer = false
  390. meek.emptyReceiveBuffer <- new(bytes.Buffer)
  391. meek.emptySendBuffer <- new(bytes.Buffer)
  392. meek.relayWaitGroup.Add(1)
  393. if meekConfig.LimitBufferSizes {
  394. meek.fullReceiveBufferLength = LIMITED_FULL_RECEIVE_BUFFER_LENGTH
  395. meek.readPayloadChunkLength = LIMITED_READ_PAYLOAD_CHUNK_LENGTH
  396. }
  397. go meek.relay()
  398. // Enable interruption
  399. if !dialConfig.PendingConns.Add(meek) {
  400. meek.Close()
  401. return nil, common.ContextError(errors.New("pending connections already closed"))
  402. }
  403. return meek, nil
  404. }
  405. type cachedTLSDialer struct {
  406. usedCachedConn int32
  407. cachedConn net.Conn
  408. dialer Dialer
  409. }
  410. func NewCachedTLSDialer(cachedConn net.Conn, dialer Dialer) *cachedTLSDialer {
  411. return &cachedTLSDialer{
  412. cachedConn: cachedConn,
  413. dialer: dialer,
  414. }
  415. }
  416. func (c *cachedTLSDialer) Dial(network, addr string) (net.Conn, error) {
  417. if atomic.CompareAndSwapInt32(&c.usedCachedConn, 0, 1) {
  418. conn := c.cachedConn
  419. c.cachedConn = nil
  420. return conn, nil
  421. }
  422. return c.dialer(network, addr)
  423. }
  424. func (c *cachedTLSDialer) Close() {
  425. if atomic.CompareAndSwapInt32(&c.usedCachedConn, 0, 1) {
  426. c.cachedConn.Close()
  427. c.cachedConn = nil
  428. }
  429. }
  430. // Close terminates the meek connection. Close waits for the relay processing goroutine
  431. // to stop and releases HTTP transport resources.
  432. // A mutex is required to support net.Conn concurrency semantics.
  433. func (meek *MeekConn) Close() (err error) {
  434. meek.mutex.Lock()
  435. isClosed := meek.isClosed
  436. meek.isClosed = true
  437. meek.mutex.Unlock()
  438. if !isClosed {
  439. meek.stopRunning()
  440. meek.pendingConns.CloseAll()
  441. if meek.cachedTLSDialer != nil {
  442. meek.cachedTLSDialer.Close()
  443. }
  444. meek.relayWaitGroup.Wait()
  445. meek.transport.CloseIdleConnections()
  446. }
  447. return nil
  448. }
  449. // IsClosed implements the Closer iterface. The return value
  450. // indicates whether the MeekConn has been closed.
  451. func (meek *MeekConn) IsClosed() bool {
  452. meek.mutex.Lock()
  453. isClosed := meek.isClosed
  454. meek.mutex.Unlock()
  455. return isClosed
  456. }
  457. // Read reads data from the connection.
  458. // net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
  459. func (meek *MeekConn) Read(buffer []byte) (n int, err error) {
  460. if meek.IsClosed() {
  461. return 0, common.ContextError(errors.New("meek connection is closed"))
  462. }
  463. // Block until there is received data to consume
  464. var receiveBuffer *bytes.Buffer
  465. select {
  466. case receiveBuffer = <-meek.partialReceiveBuffer:
  467. case receiveBuffer = <-meek.fullReceiveBuffer:
  468. case <-meek.runContext.Done():
  469. return 0, common.ContextError(errors.New("meek connection has closed"))
  470. }
  471. n, err = receiveBuffer.Read(buffer)
  472. meek.replaceReceiveBuffer(receiveBuffer)
  473. return n, err
  474. }
  475. // Write writes data to the connection.
  476. // net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
  477. func (meek *MeekConn) Write(buffer []byte) (n int, err error) {
  478. if meek.IsClosed() {
  479. return 0, common.ContextError(errors.New("meek connection is closed"))
  480. }
  481. // Repeats until all n bytes are written
  482. n = len(buffer)
  483. for len(buffer) > 0 {
  484. // Block until there is capacity in the send buffer
  485. var sendBuffer *bytes.Buffer
  486. select {
  487. case sendBuffer = <-meek.emptySendBuffer:
  488. case sendBuffer = <-meek.partialSendBuffer:
  489. case <-meek.runContext.Done():
  490. return 0, common.ContextError(errors.New("meek connection has closed"))
  491. }
  492. writeLen := MAX_SEND_PAYLOAD_LENGTH - sendBuffer.Len()
  493. if writeLen > 0 {
  494. if writeLen > len(buffer) {
  495. writeLen = len(buffer)
  496. }
  497. _, err = sendBuffer.Write(buffer[:writeLen])
  498. buffer = buffer[writeLen:]
  499. }
  500. meek.replaceSendBuffer(sendBuffer)
  501. }
  502. return n, err
  503. }
  504. // LocalAddr is a stub implementation of net.Conn.LocalAddr
  505. func (meek *MeekConn) LocalAddr() net.Addr {
  506. return nil
  507. }
  508. // RemoteAddr is a stub implementation of net.Conn.RemoteAddr
  509. func (meek *MeekConn) RemoteAddr() net.Addr {
  510. return nil
  511. }
  512. // SetDeadline is a stub implementation of net.Conn.SetDeadline
  513. func (meek *MeekConn) SetDeadline(t time.Time) error {
  514. return common.ContextError(errors.New("not supported"))
  515. }
  516. // SetReadDeadline is a stub implementation of net.Conn.SetReadDeadline
  517. func (meek *MeekConn) SetReadDeadline(t time.Time) error {
  518. return common.ContextError(errors.New("not supported"))
  519. }
  520. // SetWriteDeadline is a stub implementation of net.Conn.SetWriteDeadline
  521. func (meek *MeekConn) SetWriteDeadline(t time.Time) error {
  522. return common.ContextError(errors.New("not supported"))
  523. }
  524. func (meek *MeekConn) replaceReceiveBuffer(receiveBuffer *bytes.Buffer) {
  525. switch {
  526. case receiveBuffer.Len() == 0:
  527. meek.emptyReceiveBuffer <- receiveBuffer
  528. case receiveBuffer.Len() >= meek.fullReceiveBufferLength:
  529. meek.fullReceiveBuffer <- receiveBuffer
  530. default:
  531. meek.partialReceiveBuffer <- receiveBuffer
  532. }
  533. }
  534. func (meek *MeekConn) replaceSendBuffer(sendBuffer *bytes.Buffer) {
  535. switch {
  536. case sendBuffer.Len() == 0:
  537. meek.emptySendBuffer <- sendBuffer
  538. case sendBuffer.Len() >= MAX_SEND_PAYLOAD_LENGTH:
  539. meek.fullSendBuffer <- sendBuffer
  540. default:
  541. meek.partialSendBuffer <- sendBuffer
  542. }
  543. }
  544. // relay sends and receives tunneled traffic (payload). An HTTP request is
  545. // triggered when data is in the write queue or at a polling interval.
  546. // There's a geometric increase, up to a maximum, in the polling interval when
  547. // no data is exchanged. Only one HTTP request is in flight at a time.
  548. func (meek *MeekConn) relay() {
  549. // Note: meek.Close() calls here in relay() are made asynchronously
  550. // (using goroutines) since Close() will wait on this WaitGroup.
  551. defer meek.relayWaitGroup.Done()
  552. interval := common.JitterDuration(
  553. MIN_POLL_INTERVAL,
  554. MIN_POLL_INTERVAL_JITTER)
  555. timeout := time.NewTimer(interval)
  556. for {
  557. timeout.Reset(interval)
  558. // Block until there is payload to send or it is time to poll
  559. var sendBuffer *bytes.Buffer
  560. select {
  561. case sendBuffer = <-meek.partialSendBuffer:
  562. case sendBuffer = <-meek.fullSendBuffer:
  563. case <-timeout.C:
  564. // In the polling case, send an empty payload
  565. case <-meek.runContext.Done():
  566. // Drop through to second Done() check
  567. }
  568. // Check Done() again, to ensure it takes precedence
  569. select {
  570. case <-meek.runContext.Done():
  571. return
  572. default:
  573. }
  574. sendPayloadSize := 0
  575. if sendBuffer != nil {
  576. sendPayloadSize = sendBuffer.Len()
  577. }
  578. // roundTrip will replace sendBuffer (by calling replaceSendBuffer). This is
  579. // a compromise to conserve memory. Using a second buffer here, we could copy
  580. // sendBuffer and immediately replace it, unblocking meekConn.Write() and
  581. // allowing more upstream payload to immediately enqueue. Instead, the request
  582. // payload is read directly from sendBuffer, including retries. Only once the
  583. // server has acknowledged the request payload is sendBuffer replaced. This
  584. // still allows meekConn.Write() to unblock before the round trip response is
  585. // read.
  586. receivedPayloadSize, err := meek.roundTrip(sendBuffer)
  587. if err != nil {
  588. select {
  589. case <-meek.runContext.Done():
  590. // In this case, meek.roundTrip encountered Done(). Exit without logging error.
  591. return
  592. default:
  593. }
  594. NoticeAlert("%s", common.ContextError(err))
  595. go meek.Close()
  596. return
  597. }
  598. // Calculate polling interval. When data is received,
  599. // immediately request more. Otherwise, schedule next
  600. // poll with exponential back off. Jitter and coin
  601. // flips are used to avoid trivial, static traffic
  602. // timing patterns.
  603. if receivedPayloadSize > 0 || sendPayloadSize > 0 {
  604. interval = 0
  605. } else if interval == 0 {
  606. interval = common.JitterDuration(
  607. MIN_POLL_INTERVAL,
  608. MIN_POLL_INTERVAL_JITTER)
  609. } else {
  610. if common.FlipCoin() {
  611. interval = common.JitterDuration(
  612. interval,
  613. POLL_INTERVAL_JITTER)
  614. } else {
  615. interval = common.JitterDuration(
  616. time.Duration(float64(interval)*POLL_INTERVAL_MULTIPLIER),
  617. POLL_INTERVAL_JITTER)
  618. }
  619. if interval >= MAX_POLL_INTERVAL {
  620. interval = common.JitterDuration(
  621. MAX_POLL_INTERVAL,
  622. MAX_POLL_INTERVAL_JITTER)
  623. }
  624. }
  625. }
  626. }
  627. // readCloseSignaller is an io.ReadCloser wrapper for an io.Reader
  628. // that is passed, as the request body, to http.Transport.RoundTrip.
  629. // readCloseSignaller adds the AwaitClosed call, which is used
  630. // to schedule recycling the buffer underlying the reader only after
  631. // RoundTrip has called Close and will no longer use the buffer.
  632. // See: https://golang.org/pkg/net/http/#RoundTripper
  633. type readCloseSignaller struct {
  634. reader io.Reader
  635. closed chan struct{}
  636. }
  637. func NewReadCloseSignaller(reader io.Reader) *readCloseSignaller {
  638. return &readCloseSignaller{
  639. reader: reader,
  640. closed: make(chan struct{}, 1),
  641. }
  642. }
  643. func (r *readCloseSignaller) Read(p []byte) (int, error) {
  644. return r.reader.Read(p)
  645. }
  646. func (r *readCloseSignaller) Close() error {
  647. select {
  648. case r.closed <- *new(struct{}):
  649. default:
  650. }
  651. return nil
  652. }
  653. func (r *readCloseSignaller) AwaitClosed() {
  654. <-r.closed
  655. }
  656. // roundTrip configures and makes the actual HTTP POST request
  657. func (meek *MeekConn) roundTrip(sendBuffer *bytes.Buffer) (int64, error) {
  658. // Retries are made when the round trip fails. This adds resiliency
  659. // to connection interruption and intermittent failures.
  660. //
  661. // At least one retry is always attempted, and retries continue
  662. // while still within a brief deadline -- 5 seconds, currently the
  663. // deadline for an actively probed SSH connection to timeout. There
  664. // is a brief delay between retries, allowing for intermittent
  665. // failure states to resolve.
  666. //
  667. // Failure may occur at various stages of the HTTP request:
  668. //
  669. // 1. Before the request begins. In this case, the entire request
  670. // may be rerun.
  671. //
  672. // 2. While sending the request payload. In this case, the client
  673. // must resend its request payload. The server will not have
  674. // relayed its partially received request payload.
  675. //
  676. // 3. After sending the request payload but before receiving
  677. // a response. The client cannot distinguish between case 2 and
  678. // this case, case 3. The client resends its payload and the
  679. // server detects this and skips relaying the request payload.
  680. //
  681. // 4. While reading the response payload. The client will omit its
  682. // request payload when retrying, as the server has already
  683. // acknowledged it. The client will also indicate to the server
  684. // the amount of response payload already received, and the
  685. // server will skip resending the indicated amount of response
  686. // payload.
  687. //
  688. // Retries are indicated to the server by adding a Range header,
  689. // which includes the response payload resend position.
  690. defer func() {
  691. // Ensure sendBuffer is replaced, even in error code paths.
  692. if sendBuffer != nil {
  693. sendBuffer.Truncate(0)
  694. meek.replaceSendBuffer(sendBuffer)
  695. }
  696. }()
  697. retries := uint(0)
  698. retryDeadline := monotime.Now().Add(MEEK_ROUND_TRIP_RETRY_DEADLINE)
  699. retryDelay := MEEK_ROUND_TRIP_RETRY_MIN_DELAY
  700. serverAcknowledgedRequestPayload := false
  701. receivedPayloadSize := int64(0)
  702. for try := 0; ; try++ {
  703. // Omit the request payload when retrying after receiving a
  704. // partial server response.
  705. var signaller *readCloseSignaller
  706. var requestBody io.ReadCloser
  707. contentLength := 0
  708. if !serverAcknowledgedRequestPayload && sendBuffer != nil {
  709. // sendBuffer will be replaced once the data is no longer needed,
  710. // when RoundTrip calls Close on the Body; this allows meekConn.Write()
  711. // to unblock and start buffering data for the next roung trip while
  712. // still reading the current round trip response. signaller provides
  713. // the hook for awaiting RoundTrip's call to Close.
  714. signaller = NewReadCloseSignaller(bytes.NewReader(sendBuffer.Bytes()))
  715. requestBody = signaller
  716. contentLength = sendBuffer.Len()
  717. }
  718. var request *http.Request
  719. request, err := http.NewRequest("POST", meek.url.String(), requestBody)
  720. if err != nil {
  721. // Don't retry when can't initialize a Request
  722. return 0, common.ContextError(err)
  723. }
  724. // Content-Length won't be set automatically due to the underlying
  725. // type of requestBody.
  726. if contentLength > 0 {
  727. request.ContentLength = int64(contentLength)
  728. }
  729. // - meek.stopRunning() will abort a round trip in flight
  730. // - round trip will abort if it exceeds MEEK_ROUND_TRIP_TIMEOUT
  731. requestContext, cancelFunc := context.WithTimeout(
  732. meek.runContext,
  733. MEEK_ROUND_TRIP_TIMEOUT)
  734. defer cancelFunc()
  735. request = request.WithContext(requestContext)
  736. meek.addAdditionalHeaders(request)
  737. request.Header.Set("Content-Type", "application/octet-stream")
  738. request.AddCookie(meek.cookie)
  739. expectedStatusCode := http.StatusOK
  740. // When retrying, add a Range header to indicate how much
  741. // of the response was already received.
  742. if try > 0 {
  743. expectedStatusCode = http.StatusPartialContent
  744. request.Header.Set("Range", fmt.Sprintf("bytes=%d-", receivedPayloadSize))
  745. }
  746. response, err := meek.transport.RoundTrip(request)
  747. // Wait for RoundTrip to call Close on the request body, when
  748. // there is one. This is necessary to ensure it's safe to
  749. // subsequently replace sendBuffer in both the success and
  750. // error cases.
  751. if signaller != nil {
  752. signaller.AwaitClosed()
  753. }
  754. if err != nil {
  755. select {
  756. case <-meek.runContext.Done():
  757. // Exit without retrying and without logging error.
  758. return 0, common.ContextError(err)
  759. default:
  760. }
  761. NoticeAlert("meek round trip failed: %s", err)
  762. // ...continue to retry
  763. }
  764. if err == nil {
  765. if response.StatusCode != expectedStatusCode &&
  766. // Certain http servers return 200 OK where we expect 206, so accept that.
  767. !(expectedStatusCode == http.StatusPartialContent && response.StatusCode == http.StatusOK) {
  768. // Don't retry when the status code is incorrect
  769. response.Body.Close()
  770. return 0, common.ContextError(
  771. fmt.Errorf(
  772. "unexpected status code: %d instead of %d",
  773. response.StatusCode, expectedStatusCode))
  774. }
  775. // Update meek session cookie
  776. for _, c := range response.Cookies() {
  777. if meek.cookie.Name == c.Name {
  778. meek.cookie.Value = c.Value
  779. break
  780. }
  781. }
  782. // Received the response status code, so the server
  783. // must have received the request payload.
  784. serverAcknowledgedRequestPayload = true
  785. // sendBuffer is now no longer required for retries, and the
  786. // buffer may be replaced; this allows meekConn.Write() to unblock
  787. // and start buffering data for the next round trip while still
  788. // reading the current round trip response.
  789. if sendBuffer != nil {
  790. // Assumes signaller.AwaitClosed is called above, so
  791. // sendBuffer will no longer be accessed by RoundTrip.
  792. sendBuffer.Truncate(0)
  793. meek.replaceSendBuffer(sendBuffer)
  794. sendBuffer = nil
  795. }
  796. readPayloadSize, err := meek.readPayload(response.Body)
  797. response.Body.Close()
  798. // receivedPayloadSize is the number of response
  799. // payload bytes received and relayed. A retry can
  800. // resume after this position.
  801. receivedPayloadSize += readPayloadSize
  802. if err != nil {
  803. NoticeAlert("meek read payload failed: %s", err)
  804. // ...continue to retry
  805. } else {
  806. // Round trip completed successfully
  807. break
  808. }
  809. }
  810. // Release context resources now.
  811. cancelFunc()
  812. // Either the request failed entirely, or there was a failure
  813. // streaming the response payload. Always retry once. Then
  814. // retry if time remains; when the next delay exceeds the time
  815. // remaining until the deadline, do not retry.
  816. now := monotime.Now()
  817. if retries >= 1 &&
  818. (now.After(retryDeadline) || retryDeadline.Sub(now) <= retryDelay) {
  819. return 0, common.ContextError(err)
  820. }
  821. retries += 1
  822. delayTimer := time.NewTimer(retryDelay)
  823. select {
  824. case <-delayTimer.C:
  825. case <-meek.runContext.Done():
  826. return 0, common.ContextError(err)
  827. }
  828. // Increase the next delay, to back off and avoid excessive
  829. // activity in conditions such as no network connectivity.
  830. retryDelay *= MEEK_ROUND_TRIP_RETRY_MULTIPLIER
  831. if retryDelay >= MEEK_ROUND_TRIP_RETRY_MAX_DELAY {
  832. retryDelay = MEEK_ROUND_TRIP_RETRY_MAX_DELAY
  833. }
  834. }
  835. return receivedPayloadSize, nil
  836. }
  837. // Add additional headers to the HTTP request using the same method we use for adding
  838. // custom headers to HTTP proxy requests.
  839. func (meek *MeekConn) addAdditionalHeaders(request *http.Request) {
  840. for name, value := range meek.additionalHeaders {
  841. // hack around special case of "Host" header
  842. // https://golang.org/src/net/http/request.go#L474
  843. // using URL.Opaque, see URL.RequestURI() https://golang.org/src/net/url/url.go#L915
  844. if name == "Host" {
  845. if len(value) > 0 {
  846. if request.URL.Opaque == "" {
  847. request.URL.Opaque = request.URL.Scheme + "://" + request.Host + request.URL.RequestURI()
  848. }
  849. request.Host = value[0]
  850. }
  851. } else {
  852. request.Header[name] = value
  853. }
  854. }
  855. }
  856. // readPayload reads the HTTP response in chunks, making the read buffer available
  857. // to MeekConn.Read() calls after each chunk; the intention is to allow bytes to
  858. // flow back to the reader as soon as possible instead of buffering the entire payload.
  859. //
  860. // When readPayload returns an error, the totalSize output is remains valid -- it's the
  861. // number of payload bytes successfully read and relayed.
  862. func (meek *MeekConn) readPayload(
  863. receivedPayload io.ReadCloser) (totalSize int64, err error) {
  864. defer receivedPayload.Close()
  865. totalSize = 0
  866. for {
  867. reader := io.LimitReader(receivedPayload, int64(meek.readPayloadChunkLength))
  868. // Block until there is capacity in the receive buffer
  869. var receiveBuffer *bytes.Buffer
  870. select {
  871. case receiveBuffer = <-meek.emptyReceiveBuffer:
  872. case receiveBuffer = <-meek.partialReceiveBuffer:
  873. case <-meek.runContext.Done():
  874. return 0, nil
  875. }
  876. // Note: receiveBuffer size may exceed meek.fullReceiveBufferLength by up to the size
  877. // of one received payload. The meek.fullReceiveBufferLength value is just a guideline.
  878. n, err := receiveBuffer.ReadFrom(reader)
  879. meek.replaceReceiveBuffer(receiveBuffer)
  880. totalSize += n
  881. if err != nil {
  882. return totalSize, common.ContextError(err)
  883. }
  884. if n == 0 {
  885. break
  886. }
  887. }
  888. return totalSize, nil
  889. }
  890. // makeCookie creates the cookie to be sent with initial meek HTTP request.
  891. // The purpose of the cookie is to send the following to the server:
  892. // ServerAddress -- the Psiphon Server address the meek server should relay to
  893. // SessionID -- the Psiphon session ID (used by meek server to relay geolocation
  894. // information obtained from the CDN through to the Psiphon Server)
  895. // MeekProtocolVersion -- tells the meek server that this client understands
  896. // the latest protocol.
  897. // The server will create a session using these values and send the session ID
  898. // back to the client via Set-Cookie header. Client must use that value with
  899. // all consequent HTTP requests
  900. // In unfronted meek mode, the cookie is visible over the adversary network, so the
  901. // cookie is encrypted and obfuscated.
  902. func makeMeekCookie(meekConfig *MeekConfig) (cookie *http.Cookie, err error) {
  903. // Make the JSON data
  904. serverAddress := meekConfig.PsiphonServerAddress
  905. cookieData := &protocol.MeekCookieData{
  906. ServerAddress: serverAddress,
  907. SessionID: meekConfig.SessionID,
  908. MeekProtocolVersion: MEEK_PROTOCOL_VERSION,
  909. ClientTunnelProtocol: meekConfig.ClientTunnelProtocol,
  910. }
  911. serializedCookie, err := json.Marshal(cookieData)
  912. if err != nil {
  913. return nil, common.ContextError(err)
  914. }
  915. // Encrypt the JSON data
  916. // NaCl box is used for encryption. The peer public key comes from the server entry.
  917. // Nonce is always all zeros, and is not sent in the cookie (the server also uses an all-zero nonce).
  918. // http://nacl.cace-project.eu/box.html:
  919. // "There is no harm in having the same nonce for different messages if the {sender, receiver} sets are
  920. // different. This is true even if the sets overlap. For example, a sender can use the same nonce for two
  921. // different messages if the messages are sent to two different public keys."
  922. var nonce [24]byte
  923. var publicKey [32]byte
  924. decodedPublicKey, err := base64.StdEncoding.DecodeString(meekConfig.MeekCookieEncryptionPublicKey)
  925. if err != nil {
  926. return nil, common.ContextError(err)
  927. }
  928. copy(publicKey[:], decodedPublicKey)
  929. ephemeralPublicKey, ephemeralPrivateKey, err := box.GenerateKey(rand.Reader)
  930. if err != nil {
  931. return nil, common.ContextError(err)
  932. }
  933. box := box.Seal(nil, serializedCookie, &nonce, &publicKey, ephemeralPrivateKey)
  934. encryptedCookie := make([]byte, 32+len(box))
  935. copy(encryptedCookie[0:32], ephemeralPublicKey[0:32])
  936. copy(encryptedCookie[32:], box)
  937. // Obfuscate the encrypted data
  938. obfuscator, err := common.NewClientObfuscator(
  939. &common.ObfuscatorConfig{Keyword: meekConfig.MeekObfuscatedKey, MaxPadding: MEEK_COOKIE_MAX_PADDING})
  940. if err != nil {
  941. return nil, common.ContextError(err)
  942. }
  943. obfuscatedCookie := obfuscator.SendSeedMessage()
  944. seedLen := len(obfuscatedCookie)
  945. obfuscatedCookie = append(obfuscatedCookie, encryptedCookie...)
  946. obfuscator.ObfuscateClientToServer(obfuscatedCookie[seedLen:])
  947. // Format the HTTP cookie
  948. // The format is <random letter 'A'-'Z'>=<base64 data>, which is intended to match common cookie formats.
  949. A := int('A')
  950. Z := int('Z')
  951. // letterIndex is integer in range [int('A'), int('Z')]
  952. letterIndex, err := common.MakeSecureRandomInt(Z - A + 1)
  953. if err != nil {
  954. return nil, common.ContextError(err)
  955. }
  956. return &http.Cookie{
  957. Name: string(byte(A + letterIndex)),
  958. Value: base64.StdEncoding.EncodeToString(obfuscatedCookie)},
  959. nil
  960. }