inproxy_test.go 27 KB

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