inproxy_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. //go:build PSIPHON_ENABLE_INPROXY
  2. /*
  3. * Copyright (c) 2023, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package inproxy
  21. import (
  22. "bytes"
  23. "context"
  24. "crypto/tls"
  25. "encoding/base64"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. _ "net/http/pprof"
  32. "strconv"
  33. "strings"
  34. "sync"
  35. "sync/atomic"
  36. "testing"
  37. "time"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  43. "golang.org/x/sync/errgroup"
  44. )
  45. func TestInproxy(t *testing.T) {
  46. err := runTestInproxy()
  47. if err != nil {
  48. t.Errorf(errors.Trace(err).Error())
  49. }
  50. }
  51. func runTestInproxy() error {
  52. // Note: use the environment variable PION_LOG_TRACE=all to emit WebRTC logging.
  53. numProxies := 5
  54. proxyMaxClients := 3
  55. numClients := 10
  56. bytesToSend := 1 << 20
  57. targetElapsedSeconds := 2
  58. baseAPIParameters := common.APIParameters{
  59. "sponsor_id": strings.ToUpper(prng.HexString(8)),
  60. "client_platform": "test-client-platform",
  61. }
  62. testCompartmentID, _ := MakeID()
  63. testCommonCompartmentIDs := []ID{testCompartmentID}
  64. testNetworkID := "NETWORK-ID-1"
  65. testNetworkType := NetworkTypeUnknown
  66. testNATType := NATTypeUnknown
  67. testSTUNServerAddress := "stun.nextcloud.com:443"
  68. testDisableSTUN := false
  69. testNewTacticsPayload := []byte(prng.HexString(100))
  70. testNewTacticsTag := "new-tactics-tag"
  71. testUnchangedTacticsPayload := []byte(prng.HexString(100))
  72. // TODO: test port mapping
  73. stunServerAddressSucceededCount := int32(0)
  74. stunServerAddressSucceeded := func(bool, string) { atomic.AddInt32(&stunServerAddressSucceededCount, 1) }
  75. stunServerAddressFailedCount := int32(0)
  76. stunServerAddressFailed := func(bool, string) { atomic.AddInt32(&stunServerAddressFailedCount, 1) }
  77. roundTripperSucceededCount := int32(0)
  78. roundTripperSucceded := func(RoundTripper) { atomic.AddInt32(&roundTripperSucceededCount, 1) }
  79. roundTripperFailedCount := int32(0)
  80. roundTripperFailed := func(RoundTripper) { atomic.AddInt32(&roundTripperFailedCount, 1) }
  81. testCtx, stopTest := context.WithCancel(context.Background())
  82. defer stopTest()
  83. testGroup := new(errgroup.Group)
  84. // Enable test to run without requiring host firewall exceptions
  85. SetAllowBogonWebRTCConnections(true)
  86. // Init logging and profiling
  87. logger := newTestLogger()
  88. pprofListener, err := net.Listen("tcp", "127.0.0.1:0")
  89. go http.Serve(pprofListener, nil)
  90. defer pprofListener.Close()
  91. logger.WithTrace().Info(fmt.Sprintf("PPROF: http://%s/debug/pprof", pprofListener.Addr()))
  92. // Start echo servers
  93. tcpEchoListener, err := net.Listen("tcp", "127.0.0.1:0")
  94. if err != nil {
  95. return errors.Trace(err)
  96. }
  97. defer tcpEchoListener.Close()
  98. go runTCPEchoServer(tcpEchoListener)
  99. // QUIC tests UDP proxying, and provides reliable delivery of echoed data
  100. quicEchoServer, err := newQuicEchoServer()
  101. if err != nil {
  102. return errors.Trace(err)
  103. }
  104. defer quicEchoServer.Close()
  105. go quicEchoServer.Run()
  106. // Create signed server entry with capability
  107. serverPrivateKey, err := GenerateSessionPrivateKey()
  108. if err != nil {
  109. return errors.Trace(err)
  110. }
  111. serverPublicKey, err := serverPrivateKey.GetPublicKey()
  112. if err != nil {
  113. return errors.Trace(err)
  114. }
  115. serverRootObfuscationSecret, err := GenerateRootObfuscationSecret()
  116. if err != nil {
  117. return errors.Trace(err)
  118. }
  119. serverEntry := make(protocol.ServerEntryFields)
  120. serverEntry["ipAddress"] = "127.0.0.1"
  121. _, tcpPort, _ := net.SplitHostPort(tcpEchoListener.Addr().String())
  122. _, udpPort, _ := net.SplitHostPort(quicEchoServer.Addr().String())
  123. serverEntry["inproxyOSSHPort"], _ = strconv.Atoi(tcpPort)
  124. serverEntry["inproxyQUICPort"], _ = strconv.Atoi(udpPort)
  125. serverEntry["capabilities"] = []string{"INPROXY-WEBRTC-OSSH", "INPROXY-WEBRTC-QUIC-OSSH"}
  126. serverEntry["inproxySessionPublicKey"] = base64.RawStdEncoding.EncodeToString(serverPublicKey[:])
  127. serverEntry["inproxySessionRootObfuscationSecret"] = base64.RawStdEncoding.EncodeToString(serverRootObfuscationSecret[:])
  128. testServerEntryTag := prng.HexString(16)
  129. serverEntry["tag"] = testServerEntryTag
  130. serverEntrySignaturePublicKey, serverEntrySignaturePrivateKey, err :=
  131. protocol.NewServerEntrySignatureKeyPair()
  132. if err != nil {
  133. return errors.Trace(err)
  134. }
  135. err = serverEntry.AddSignature(serverEntrySignaturePublicKey, serverEntrySignaturePrivateKey)
  136. if err != nil {
  137. return errors.Trace(err)
  138. }
  139. packedServerEntryFields, err := protocol.EncodePackedServerEntryFields(serverEntry)
  140. if err != nil {
  141. return errors.Trace(err)
  142. }
  143. packedDestinationServerEntry, err := protocol.CBOREncoding.Marshal(packedServerEntryFields)
  144. if err != nil {
  145. return errors.Trace(err)
  146. }
  147. // Start broker
  148. logger.WithTrace().Info("START BROKER")
  149. brokerPrivateKey, err := GenerateSessionPrivateKey()
  150. if err != nil {
  151. return errors.Trace(err)
  152. }
  153. brokerPublicKey, err := brokerPrivateKey.GetPublicKey()
  154. if err != nil {
  155. return errors.Trace(err)
  156. }
  157. brokerRootObfuscationSecret, err := GenerateRootObfuscationSecret()
  158. if err != nil {
  159. return errors.Trace(err)
  160. }
  161. brokerListener, err := net.Listen("tcp", "127.0.0.1:0")
  162. if err != nil {
  163. return errors.Trace(err)
  164. }
  165. defer brokerListener.Close()
  166. brokerConfig := &BrokerConfig{
  167. Logger: logger,
  168. CommonCompartmentIDs: testCommonCompartmentIDs,
  169. APIParameterValidator: func(params common.APIParameters) error {
  170. if len(params) != len(baseAPIParameters) {
  171. return errors.TraceNew("unexpected base API parameter count")
  172. }
  173. for name, value := range params {
  174. if value.(string) != baseAPIParameters[name].(string) {
  175. return errors.Tracef(
  176. "unexpected base API parameter: %v: %v != %v",
  177. name,
  178. value.(string),
  179. baseAPIParameters[name].(string))
  180. }
  181. }
  182. return nil
  183. },
  184. APIParameterLogFieldFormatter: func(
  185. geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  186. return common.LogFields(params)
  187. },
  188. GetTactics: func(_ common.GeoIPData, _ common.APIParameters) ([]byte, string, error) {
  189. // Exercise both new and unchanged tactics
  190. if prng.FlipCoin() {
  191. return testNewTacticsPayload, testNewTacticsTag, nil
  192. }
  193. return testUnchangedTacticsPayload, "", nil
  194. },
  195. IsValidServerEntryTag: func(serverEntryTag string) bool { return serverEntryTag == testServerEntryTag },
  196. PrivateKey: brokerPrivateKey,
  197. ObfuscationRootSecret: brokerRootObfuscationSecret,
  198. ServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  199. AllowProxy: func(common.GeoIPData) bool { return true },
  200. AllowClient: func(common.GeoIPData) bool { return true },
  201. AllowDomainFrontedDestinations: func(common.GeoIPData) bool { return true },
  202. }
  203. broker, err := NewBroker(brokerConfig)
  204. if err != nil {
  205. return errors.Trace(err)
  206. }
  207. err = broker.Start()
  208. if err != nil {
  209. return errors.Trace(err)
  210. }
  211. defer broker.Stop()
  212. testGroup.Go(func() error {
  213. err := runHTTPServer(brokerListener, broker)
  214. if testCtx.Err() != nil {
  215. return nil
  216. }
  217. return errors.Trace(err)
  218. })
  219. // Stub server broker request handler (in Psiphon, this will be the
  220. // destination Psiphon server; here, it's not necessary to build this
  221. // handler into the destination echo server)
  222. serverSessions, err := NewServerBrokerSessions(
  223. serverPrivateKey, serverRootObfuscationSecret, []SessionPublicKey{brokerPublicKey})
  224. if err != nil {
  225. return errors.Trace(err)
  226. }
  227. var pendingBrokerServerReportsMutex sync.Mutex
  228. pendingBrokerServerReports := make(map[ID]bool)
  229. addPendingBrokerServerReport := func(connectionID ID) {
  230. pendingBrokerServerReportsMutex.Lock()
  231. defer pendingBrokerServerReportsMutex.Unlock()
  232. pendingBrokerServerReports[connectionID] = true
  233. }
  234. hasPendingBrokerServerReports := func() bool {
  235. pendingBrokerServerReportsMutex.Lock()
  236. defer pendingBrokerServerReportsMutex.Unlock()
  237. return len(pendingBrokerServerReports) > 0
  238. }
  239. handleBrokerServerReports := func(in []byte, clientConnectionID ID) ([]byte, error) {
  240. handler := func(brokerVerifiedOriginalClientIP string, logFields common.LogFields) {
  241. pendingBrokerServerReportsMutex.Lock()
  242. defer pendingBrokerServerReportsMutex.Unlock()
  243. // Mark the report as no longer outstanding
  244. delete(pendingBrokerServerReports, clientConnectionID)
  245. }
  246. out, err := serverSessions.HandlePacket(logger, in, clientConnectionID, handler)
  247. return out, errors.Trace(err)
  248. }
  249. // Check that the tactics round trip succeeds
  250. var pendingProxyTacticsCallbacksMutex sync.Mutex
  251. pendingProxyTacticsCallbacks := make(map[SessionPrivateKey]bool)
  252. addPendingProxyTacticsCallback := func(proxyPrivateKey SessionPrivateKey) {
  253. pendingProxyTacticsCallbacksMutex.Lock()
  254. defer pendingProxyTacticsCallbacksMutex.Unlock()
  255. pendingProxyTacticsCallbacks[proxyPrivateKey] = true
  256. }
  257. hasPendingProxyTacticsCallbacks := func() bool {
  258. pendingProxyTacticsCallbacksMutex.Lock()
  259. defer pendingProxyTacticsCallbacksMutex.Unlock()
  260. return len(pendingProxyTacticsCallbacks) > 0
  261. }
  262. makeHandleTacticsPayload := func(
  263. proxyPrivateKey SessionPrivateKey,
  264. tacticsNetworkID string) func(_ string, _ []byte) bool {
  265. return func(networkID string, tacticsPayload []byte) bool {
  266. pendingProxyTacticsCallbacksMutex.Lock()
  267. defer pendingProxyTacticsCallbacksMutex.Unlock()
  268. // Check that the correct networkID is passed around; if not,
  269. // skip the delete, which will fail the test
  270. if networkID == tacticsNetworkID {
  271. // Certain state is reset when new tactics are applied -- the
  272. // return true case; exercise both cases
  273. if bytes.Equal(tacticsPayload, testNewTacticsPayload) {
  274. delete(pendingProxyTacticsCallbacks, proxyPrivateKey)
  275. return true
  276. }
  277. if bytes.Equal(tacticsPayload, testUnchangedTacticsPayload) {
  278. delete(pendingProxyTacticsCallbacks, proxyPrivateKey)
  279. return false
  280. }
  281. }
  282. panic("unexpected tactics payload")
  283. }
  284. }
  285. // Start proxies
  286. logger.WithTrace().Info("START PROXIES")
  287. for i := 0; i < numProxies; i++ {
  288. proxyPrivateKey, err := GenerateSessionPrivateKey()
  289. if err != nil {
  290. return errors.Trace(err)
  291. }
  292. brokerCoordinator := &testBrokerDialCoordinator{
  293. networkID: testNetworkID,
  294. networkType: testNetworkType,
  295. brokerClientPrivateKey: proxyPrivateKey,
  296. brokerPublicKey: brokerPublicKey,
  297. brokerRootObfuscationSecret: brokerRootObfuscationSecret,
  298. brokerClientRoundTripper: newHTTPRoundTripper(
  299. brokerListener.Addr().String(), "proxy"),
  300. brokerClientRoundTripperSucceeded: roundTripperSucceded,
  301. brokerClientRoundTripperFailed: roundTripperFailed,
  302. }
  303. webRTCCoordinator := &testWebRTCDialCoordinator{
  304. networkID: testNetworkID,
  305. networkType: testNetworkType,
  306. natType: testNATType,
  307. disableSTUN: testDisableSTUN,
  308. stunServerAddress: testSTUNServerAddress,
  309. stunServerAddressRFC5780: testSTUNServerAddress,
  310. stunServerAddressSucceeded: stunServerAddressSucceeded,
  311. stunServerAddressFailed: stunServerAddressFailed,
  312. setNATType: func(NATType) {},
  313. setPortMappingTypes: func(PortMappingTypes) {},
  314. bindToDevice: func(int) error { return nil },
  315. }
  316. // Each proxy has its own broker client
  317. brokerClient, err := NewBrokerClient(brokerCoordinator)
  318. if err != nil {
  319. return errors.Trace(err)
  320. }
  321. tacticsNetworkID := prng.HexString(32)
  322. proxy, err := NewProxy(&ProxyConfig{
  323. Logger: logger,
  324. WaitForNetworkConnectivity: func() bool {
  325. return true
  326. },
  327. GetBrokerClient: func() (*BrokerClient, error) {
  328. return brokerClient, nil
  329. },
  330. GetBaseAPIParameters: func() (common.APIParameters, string, error) {
  331. return baseAPIParameters, tacticsNetworkID, nil
  332. },
  333. MakeWebRTCDialCoordinator: func() (WebRTCDialCoordinator, error) {
  334. return webRTCCoordinator, nil
  335. },
  336. HandleTacticsPayload: makeHandleTacticsPayload(proxyPrivateKey, tacticsNetworkID),
  337. MaxClients: proxyMaxClients,
  338. LimitUpstreamBytesPerSecond: bytesToSend / targetElapsedSeconds,
  339. LimitDownstreamBytesPerSecond: bytesToSend / targetElapsedSeconds,
  340. ActivityUpdater: func(connectingClients int32, connectedClients int32,
  341. bytesUp int64, bytesDown int64, bytesDuration time.Duration) {
  342. fmt.Printf("[%s] ACTIVITY: %d connecting, %d connected, %d up, %d down\n",
  343. time.Now().UTC().Format(time.RFC3339),
  344. connectingClients, connectedClients, bytesUp, bytesDown)
  345. },
  346. })
  347. if err != nil {
  348. return errors.Trace(err)
  349. }
  350. addPendingProxyTacticsCallback(proxyPrivateKey)
  351. testGroup.Go(func() error {
  352. proxy.Run(testCtx)
  353. return nil
  354. })
  355. }
  356. // Await proxy announcements before starting clients
  357. //
  358. // - Announcements may delay due to proxyAnnounceRetryDelay in Proxy.Run,
  359. // plus NAT discovery
  360. //
  361. // - Don't wait for > numProxies announcements due to
  362. // InitiatorSessions.NewRoundTrip waitToShareSession limitation
  363. for {
  364. time.Sleep(100 * time.Millisecond)
  365. broker.matcher.announcementQueueMutex.Lock()
  366. n := broker.matcher.announcementQueue.Len()
  367. broker.matcher.announcementQueueMutex.Unlock()
  368. if n >= numProxies {
  369. break
  370. }
  371. }
  372. // Start clients
  373. logger.WithTrace().Info("START CLIENTS")
  374. clientsGroup := new(errgroup.Group)
  375. makeClientFunc := func(
  376. isTCP bool,
  377. isMobile bool,
  378. brokerClient *BrokerClient,
  379. webRTCCoordinator WebRTCDialCoordinator) func() error {
  380. var networkProtocol NetworkProtocol
  381. var addr string
  382. var wrapWithQUIC bool
  383. if isTCP {
  384. networkProtocol = NetworkProtocolTCP
  385. addr = tcpEchoListener.Addr().String()
  386. } else {
  387. networkProtocol = NetworkProtocolUDP
  388. addr = quicEchoServer.Addr().String()
  389. wrapWithQUIC = true
  390. }
  391. return func() error {
  392. dialCtx, cancelDial := context.WithTimeout(testCtx, 60*time.Second)
  393. defer cancelDial()
  394. conn, err := DialClient(
  395. dialCtx,
  396. &ClientConfig{
  397. Logger: logger,
  398. BaseAPIParameters: baseAPIParameters,
  399. BrokerClient: brokerClient,
  400. WebRTCDialCoordinator: webRTCCoordinator,
  401. ReliableTransport: isTCP,
  402. DialNetworkProtocol: networkProtocol,
  403. DialAddress: addr,
  404. PackedDestinationServerEntry: packedDestinationServerEntry,
  405. })
  406. if err != nil {
  407. return errors.Trace(err)
  408. }
  409. var relayConn net.Conn
  410. relayConn = conn
  411. if wrapWithQUIC {
  412. quicConn, err := quic.Dial(
  413. dialCtx,
  414. conn,
  415. &net.UDPAddr{Port: 1}, // This address is ignored, but the zero value is not allowed
  416. "test", "QUICv1", nil, quicEchoServer.ObfuscationKey(), nil, nil, true)
  417. if err != nil {
  418. return errors.Trace(err)
  419. }
  420. relayConn = quicConn
  421. }
  422. addPendingBrokerServerReport(conn.GetConnectionID())
  423. signalRelayComplete := make(chan struct{})
  424. clientsGroup.Go(func() error {
  425. defer close(signalRelayComplete)
  426. in := conn.InitialRelayPacket()
  427. for in != nil {
  428. out, err := handleBrokerServerReports(in, conn.GetConnectionID())
  429. if err != nil {
  430. if out == nil {
  431. return errors.Trace(err)
  432. } else {
  433. fmt.Printf("HandlePacket returned packet and error: %v\n", err)
  434. // Proceed with reset session token packet
  435. }
  436. }
  437. if out == nil {
  438. // Relay is complete
  439. break
  440. }
  441. in, err = conn.RelayPacket(testCtx, out)
  442. if err != nil {
  443. return errors.Trace(err)
  444. }
  445. }
  446. return nil
  447. })
  448. sendBytes := prng.Bytes(bytesToSend)
  449. clientsGroup.Go(func() error {
  450. for n := 0; n < bytesToSend; {
  451. m := prng.Range(1024, 32768)
  452. if bytesToSend-n < m {
  453. m = bytesToSend - n
  454. }
  455. _, err := relayConn.Write(sendBytes[n : n+m])
  456. if err != nil {
  457. return errors.Trace(err)
  458. }
  459. n += m
  460. }
  461. fmt.Printf("%d bytes sent\n", bytesToSend)
  462. return nil
  463. })
  464. clientsGroup.Go(func() error {
  465. buf := make([]byte, 32768)
  466. n := 0
  467. for n < bytesToSend {
  468. m, err := relayConn.Read(buf)
  469. if err != nil {
  470. return errors.Trace(err)
  471. }
  472. if !bytes.Equal(sendBytes[n:n+m], buf[:m]) {
  473. return errors.Tracef(
  474. "unexpected bytes: expected at index %d, received at index %d",
  475. bytes.Index(sendBytes, buf[:m]), n)
  476. }
  477. n += m
  478. }
  479. fmt.Printf("%d bytes received\n", bytesToSend)
  480. select {
  481. case <-signalRelayComplete:
  482. case <-testCtx.Done():
  483. }
  484. relayConn.Close()
  485. conn.Close()
  486. return nil
  487. })
  488. return nil
  489. }
  490. }
  491. newClientParams := func(isMobile bool) (*BrokerClient, *testWebRTCDialCoordinator, error) {
  492. clientPrivateKey, err := GenerateSessionPrivateKey()
  493. if err != nil {
  494. return nil, nil, errors.Trace(err)
  495. }
  496. clientRootObfuscationSecret, err := GenerateRootObfuscationSecret()
  497. if err != nil {
  498. return nil, nil, errors.Trace(err)
  499. }
  500. brokerCoordinator := &testBrokerDialCoordinator{
  501. networkID: testNetworkID,
  502. networkType: testNetworkType,
  503. commonCompartmentIDs: testCommonCompartmentIDs,
  504. brokerClientPrivateKey: clientPrivateKey,
  505. brokerPublicKey: brokerPublicKey,
  506. brokerRootObfuscationSecret: brokerRootObfuscationSecret,
  507. brokerClientRoundTripper: newHTTPRoundTripper(
  508. brokerListener.Addr().String(), "client"),
  509. brokerClientRoundTripperSucceeded: roundTripperSucceded,
  510. brokerClientRoundTripperFailed: roundTripperFailed,
  511. }
  512. webRTCCoordinator := &testWebRTCDialCoordinator{
  513. networkID: testNetworkID,
  514. networkType: testNetworkType,
  515. natType: testNATType,
  516. disableSTUN: testDisableSTUN,
  517. stunServerAddress: testSTUNServerAddress,
  518. stunServerAddressRFC5780: testSTUNServerAddress,
  519. stunServerAddressSucceeded: stunServerAddressSucceeded,
  520. stunServerAddressFailed: stunServerAddressFailed,
  521. clientRootObfuscationSecret: clientRootObfuscationSecret,
  522. doDTLSRandomization: prng.FlipCoin(),
  523. trafficShapingParameters: &DataChannelTrafficShapingParameters{
  524. MinPaddedMessages: 0,
  525. MaxPaddedMessages: 10,
  526. MinPaddingSize: 0,
  527. MaxPaddingSize: 1500,
  528. MinDecoyMessages: 0,
  529. MaxDecoyMessages: 10,
  530. MinDecoySize: 1,
  531. MaxDecoySize: 1500,
  532. DecoyMessageProbability: 0.5,
  533. },
  534. setNATType: func(NATType) {},
  535. setPortMappingTypes: func(PortMappingTypes) {},
  536. bindToDevice: func(int) error { return nil },
  537. // With STUN enabled (testDisableSTUN = false), there are cases
  538. // where the WebRTC Data Channel is not successfully established.
  539. // With a short enough timeout here, clients will redial and
  540. // eventually succceed.
  541. webRTCAwaitDataChannelTimeout: 5 * time.Second,
  542. }
  543. if isMobile {
  544. webRTCCoordinator.networkType = NetworkTypeMobile
  545. webRTCCoordinator.disableInboundForMobileNetworks = true
  546. }
  547. brokerClient, err := NewBrokerClient(brokerCoordinator)
  548. if err != nil {
  549. return nil, nil, errors.Trace(err)
  550. }
  551. return brokerClient, webRTCCoordinator, nil
  552. }
  553. clientBrokerClient, clientWebRTCCoordinator, err := newClientParams(false)
  554. if err != nil {
  555. return errors.Trace(err)
  556. }
  557. clientMobileBrokerClient, clientMobileWebRTCCoordinator, err := newClientParams(true)
  558. if err != nil {
  559. return errors.Trace(err)
  560. }
  561. for i := 0; i < numClients; i++ {
  562. // Test a mix of TCP and UDP proxying; also test the
  563. // DisableInboundForMobileNetworks code path.
  564. isTCP := i%2 == 0
  565. isMobile := i%4 == 0
  566. // Exercise BrokerClients shared by multiple clients, but also create
  567. // several broker clients.
  568. if i%8 == 0 {
  569. clientBrokerClient, clientWebRTCCoordinator, err = newClientParams(false)
  570. if err != nil {
  571. return errors.Trace(err)
  572. }
  573. clientMobileBrokerClient, clientMobileWebRTCCoordinator, err = newClientParams(true)
  574. if err != nil {
  575. return errors.Trace(err)
  576. }
  577. }
  578. brokerClient := clientBrokerClient
  579. webRTCCoordinator := clientWebRTCCoordinator
  580. if isMobile {
  581. brokerClient = clientMobileBrokerClient
  582. webRTCCoordinator = clientMobileWebRTCCoordinator
  583. }
  584. clientsGroup.Go(makeClientFunc(isTCP, isMobile, brokerClient, webRTCCoordinator))
  585. }
  586. // Await client transfers complete
  587. logger.WithTrace().Info("AWAIT DATA TRANSFER")
  588. err = clientsGroup.Wait()
  589. if err != nil {
  590. return errors.Trace(err)
  591. }
  592. logger.WithTrace().Info("DONE DATA TRANSFER")
  593. if hasPendingBrokerServerReports() {
  594. return errors.TraceNew("unexpected pending broker server requests")
  595. }
  596. if hasPendingProxyTacticsCallbacks() {
  597. return errors.TraceNew("unexpected pending proxy tactics callback")
  598. }
  599. // TODO: check that elapsed time is consistent with rate limit (+/-)
  600. // Check if STUN server replay callbacks were triggered
  601. if !testDisableSTUN {
  602. if atomic.LoadInt32(&stunServerAddressSucceededCount) < 1 {
  603. return errors.TraceNew("unexpected STUN server succeeded count")
  604. }
  605. }
  606. if atomic.LoadInt32(&stunServerAddressFailedCount) > 0 {
  607. return errors.TraceNew("unexpected STUN server failed count")
  608. }
  609. // Check if RoundTripper server replay callbacks were triggered
  610. if atomic.LoadInt32(&roundTripperSucceededCount) < 1 {
  611. return errors.TraceNew("unexpected round tripper succeeded count")
  612. }
  613. if atomic.LoadInt32(&roundTripperFailedCount) > 0 {
  614. return errors.TraceNew("unexpected round tripper failed count")
  615. }
  616. // Await shutdowns
  617. stopTest()
  618. brokerListener.Close()
  619. err = testGroup.Wait()
  620. if err != nil {
  621. return errors.Trace(err)
  622. }
  623. return nil
  624. }
  625. func runHTTPServer(listener net.Listener, broker *Broker) error {
  626. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  627. // For this test, clients set the path to "/client" and proxies
  628. // set the path to "/proxy" and we use that to create stub GeoIP
  629. // data to pass the not-same-ASN condition.
  630. var geoIPData common.GeoIPData
  631. geoIPData.ASN = r.URL.Path
  632. requestPayload, err := ioutil.ReadAll(
  633. http.MaxBytesReader(w, r.Body, BrokerMaxRequestBodySize))
  634. if err != nil {
  635. fmt.Printf("runHTTPServer ioutil.ReadAll failed: %v\n", err)
  636. http.Error(w, "", http.StatusNotFound)
  637. return
  638. }
  639. clientIP, _, _ := net.SplitHostPort(r.RemoteAddr)
  640. extendTimeout := func(timeout time.Duration) {
  641. // TODO: set insufficient initial timeout, so extension is
  642. // required for success
  643. http.NewResponseController(w).SetWriteDeadline(time.Now().Add(timeout))
  644. }
  645. responsePayload, err := broker.HandleSessionPacket(
  646. r.Context(),
  647. extendTimeout,
  648. nil,
  649. clientIP,
  650. geoIPData,
  651. requestPayload)
  652. if err != nil {
  653. fmt.Printf("runHTTPServer HandleSessionPacket failed: %v\n", err)
  654. http.Error(w, "", http.StatusNotFound)
  655. return
  656. }
  657. w.WriteHeader(http.StatusOK)
  658. w.Write(responsePayload)
  659. })
  660. // WriteTimeout will be extended via extendTimeout.
  661. httpServer := &http.Server{
  662. ReadTimeout: 10 * time.Second,
  663. WriteTimeout: 10 * time.Second,
  664. IdleTimeout: 1 * time.Minute,
  665. Handler: handler,
  666. }
  667. certificate, privateKey, _, err := common.GenerateWebServerCertificate("www.example.com")
  668. if err != nil {
  669. return errors.Trace(err)
  670. }
  671. tlsCert, err := tls.X509KeyPair([]byte(certificate), []byte(privateKey))
  672. if err != nil {
  673. return errors.Trace(err)
  674. }
  675. tlsConfig := &tls.Config{
  676. Certificates: []tls.Certificate{tlsCert},
  677. }
  678. err = httpServer.Serve(tls.NewListener(listener, tlsConfig))
  679. return errors.Trace(err)
  680. }
  681. type httpRoundTripper struct {
  682. httpClient *http.Client
  683. endpointAddr string
  684. path string
  685. }
  686. func newHTTPRoundTripper(endpointAddr string, path string) *httpRoundTripper {
  687. return &httpRoundTripper{
  688. httpClient: &http.Client{
  689. Transport: &http.Transport{
  690. ForceAttemptHTTP2: true,
  691. MaxIdleConns: 2,
  692. IdleConnTimeout: 1 * time.Minute,
  693. TLSHandshakeTimeout: 10 * time.Second,
  694. TLSClientConfig: &tls.Config{
  695. InsecureSkipVerify: true,
  696. },
  697. },
  698. },
  699. endpointAddr: endpointAddr,
  700. path: path,
  701. }
  702. }
  703. func (r *httpRoundTripper) RoundTrip(
  704. ctx context.Context,
  705. roundTripDelay time.Duration,
  706. roundTripTimeout time.Duration,
  707. requestPayload []byte) ([]byte, error) {
  708. if roundTripDelay > 0 {
  709. common.SleepWithContext(ctx, roundTripDelay)
  710. }
  711. requestCtx, requestCancelFunc := context.WithTimeout(ctx, roundTripTimeout)
  712. defer requestCancelFunc()
  713. url := fmt.Sprintf("https://%s/%s", r.endpointAddr, r.path)
  714. request, err := http.NewRequestWithContext(
  715. requestCtx, "POST", url, bytes.NewReader(requestPayload))
  716. if err != nil {
  717. return nil, errors.Trace(err)
  718. }
  719. response, err := r.httpClient.Do(request)
  720. if err != nil {
  721. return nil, errors.Trace(err)
  722. }
  723. defer response.Body.Close()
  724. if response.StatusCode != http.StatusOK {
  725. return nil, errors.Tracef("unexpected response status code: %d", response.StatusCode)
  726. }
  727. responsePayload, err := io.ReadAll(response.Body)
  728. if err != nil {
  729. return nil, errors.Trace(err)
  730. }
  731. return responsePayload, nil
  732. }
  733. func (r *httpRoundTripper) Close() error {
  734. r.httpClient.CloseIdleConnections()
  735. return nil
  736. }
  737. func runTCPEchoServer(listener net.Listener) {
  738. for {
  739. conn, err := listener.Accept()
  740. if err != nil {
  741. fmt.Printf("runTCPEchoServer failed: %v\n", errors.Trace(err))
  742. return
  743. }
  744. go func(conn net.Conn) {
  745. buf := make([]byte, 32768)
  746. for {
  747. n, err := conn.Read(buf)
  748. if n > 0 {
  749. _, err = conn.Write(buf[:n])
  750. }
  751. if err != nil {
  752. fmt.Printf("runTCPEchoServer failed: %v\n", errors.Trace(err))
  753. return
  754. }
  755. }
  756. }(conn)
  757. }
  758. }
  759. type quicEchoServer struct {
  760. listener net.Listener
  761. obfuscationKey string
  762. }
  763. func newQuicEchoServer() (*quicEchoServer, error) {
  764. obfuscationKey := prng.HexString(32)
  765. listener, err := quic.Listen(
  766. nil,
  767. nil,
  768. "127.0.0.1:0",
  769. obfuscationKey,
  770. false)
  771. if err != nil {
  772. return nil, errors.Trace(err)
  773. }
  774. return &quicEchoServer{
  775. listener: listener,
  776. obfuscationKey: obfuscationKey,
  777. }, nil
  778. }
  779. func (q *quicEchoServer) ObfuscationKey() string {
  780. return q.obfuscationKey
  781. }
  782. func (q *quicEchoServer) Close() error {
  783. return q.listener.Close()
  784. }
  785. func (q *quicEchoServer) Addr() net.Addr {
  786. return q.listener.Addr()
  787. }
  788. func (q *quicEchoServer) Run() {
  789. for {
  790. conn, err := q.listener.Accept()
  791. if err != nil {
  792. fmt.Printf("quicEchoServer failed: %v\n", errors.Trace(err))
  793. return
  794. }
  795. go func(conn net.Conn) {
  796. buf := make([]byte, 32768)
  797. for {
  798. n, err := conn.Read(buf)
  799. if n > 0 {
  800. _, err = conn.Write(buf[:n])
  801. }
  802. if err != nil {
  803. fmt.Printf("quicEchoServer failed: %v\n", errors.Trace(err))
  804. return
  805. }
  806. }
  807. }(conn)
  808. }
  809. }