controller_test.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. "context"
  22. "encoding/json"
  23. "flag"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "log"
  28. "net"
  29. "net/http"
  30. "net/url"
  31. "os"
  32. "strings"
  33. "sync"
  34. "sync/atomic"
  35. "testing"
  36. "time"
  37. socks "github.com/Psiphon-Labs/goptlib"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  42. "github.com/elazarl/goproxy"
  43. "github.com/elazarl/goproxy/ext/auth"
  44. )
  45. const testClientPlatform = "test_github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  46. func TestMain(m *testing.M) {
  47. flag.Parse()
  48. SetEmitDiagnosticNotices(true, true)
  49. initDisruptor()
  50. initUpstreamProxy()
  51. os.Exit(m.Run())
  52. }
  53. // Test case notes/limitations/dependencies:
  54. //
  55. // * Untunneled upgrade tests must execute before
  56. // the other tests to ensure no tunnel is established.
  57. // We need a way to reset the datastore after it's been
  58. // initialized in order to to clear out its data entries
  59. // and be able to arbitrarily order the tests.
  60. //
  61. // * The resumable download tests using disruptNetwork
  62. // depend on the download object being larger than the
  63. // disruptorMax limits so that the disruptor will actually
  64. // interrupt the first download attempt. Specifically, the
  65. // upgrade and remote server list at the URLs specified in
  66. // controller_test.config.enc.
  67. //
  68. // * The protocol tests assume there is at least one server
  69. // supporting each protocol in the server list at the URL
  70. // specified in controller_test.config.enc, and that these
  71. // servers are not overloaded.
  72. //
  73. // * fetchAndVerifyWebsite depends on the target URL being
  74. // available and responding.
  75. //
  76. func TestUntunneledUpgradeDownload(t *testing.T) {
  77. controllerRun(t,
  78. &controllerRunConfig{
  79. expectNoServerEntries: true,
  80. protocol: "",
  81. disableEstablishing: true,
  82. })
  83. }
  84. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  85. controllerRun(t,
  86. &controllerRunConfig{
  87. expectNoServerEntries: true,
  88. protocol: "",
  89. disableEstablishing: true,
  90. disruptNetwork: true,
  91. })
  92. }
  93. func TestUntunneledUpgradeClientIsLatestVersion(t *testing.T) {
  94. controllerRun(t,
  95. &controllerRunConfig{
  96. expectNoServerEntries: true,
  97. protocol: "",
  98. clientIsLatestVersion: true,
  99. disableEstablishing: true,
  100. })
  101. }
  102. func TestUntunneledResumableFetchRemoteServerList(t *testing.T) {
  103. controllerRun(t,
  104. &controllerRunConfig{
  105. expectNoServerEntries: true,
  106. protocol: "",
  107. clientIsLatestVersion: true,
  108. disruptNetwork: true,
  109. })
  110. }
  111. func TestTunneledUpgradeClientIsLatestVersion(t *testing.T) {
  112. controllerRun(t,
  113. &controllerRunConfig{
  114. protocol: "",
  115. clientIsLatestVersion: true,
  116. disableUntunneledUpgrade: true,
  117. })
  118. }
  119. func TestSSH(t *testing.T) {
  120. controllerRun(t,
  121. &controllerRunConfig{
  122. protocol: protocol.TUNNEL_PROTOCOL_SSH,
  123. disableUntunneledUpgrade: true,
  124. })
  125. }
  126. func TestObfuscatedSSH(t *testing.T) {
  127. controllerRun(t,
  128. &controllerRunConfig{
  129. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  130. disableUntunneledUpgrade: true,
  131. })
  132. }
  133. func TestTLS(t *testing.T) {
  134. t.Skipf("temporarily disabled")
  135. controllerRun(t,
  136. &controllerRunConfig{
  137. protocol: protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH,
  138. disableUntunneledUpgrade: true,
  139. })
  140. }
  141. func TestUnfrontedMeek(t *testing.T) {
  142. controllerRun(t,
  143. &controllerRunConfig{
  144. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  145. disableUntunneledUpgrade: true,
  146. })
  147. }
  148. func TestUnfrontedMeekWithTransformer(t *testing.T) {
  149. controllerRun(t,
  150. &controllerRunConfig{
  151. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  152. disableUntunneledUpgrade: true,
  153. transformHostNames: true,
  154. })
  155. }
  156. func TestFrontedMeek(t *testing.T) {
  157. controllerRun(t,
  158. &controllerRunConfig{
  159. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  160. disableUntunneledUpgrade: true,
  161. })
  162. }
  163. func TestFrontedMeekWithTransformer(t *testing.T) {
  164. controllerRun(t,
  165. &controllerRunConfig{
  166. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  167. disableUntunneledUpgrade: true,
  168. transformHostNames: true,
  169. })
  170. }
  171. func TestFrontedMeekHTTP(t *testing.T) {
  172. controllerRun(t,
  173. &controllerRunConfig{
  174. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP,
  175. disableUntunneledUpgrade: true,
  176. })
  177. }
  178. func TestUnfrontedMeekHTTPS(t *testing.T) {
  179. controllerRun(t,
  180. &controllerRunConfig{
  181. expectNoServerEntries: false,
  182. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  183. disableUntunneledUpgrade: true,
  184. })
  185. }
  186. func TestUnfrontedMeekHTTPSWithTransformer(t *testing.T) {
  187. controllerRun(t,
  188. &controllerRunConfig{
  189. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  190. clientIsLatestVersion: true,
  191. transformHostNames: true,
  192. })
  193. }
  194. func TestDisabledApi(t *testing.T) {
  195. controllerRun(t,
  196. &controllerRunConfig{
  197. protocol: "",
  198. clientIsLatestVersion: true,
  199. disableUntunneledUpgrade: true,
  200. disableApi: true,
  201. tunnelPoolSize: 1,
  202. })
  203. }
  204. func TestObfuscatedSSHWithUpstreamProxy(t *testing.T) {
  205. controllerRun(t,
  206. &controllerRunConfig{
  207. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  208. disableUntunneledUpgrade: true,
  209. useUpstreamProxy: true,
  210. })
  211. }
  212. func TestUnfrontedMeekWithUpstreamProxy(t *testing.T) {
  213. controllerRun(t,
  214. &controllerRunConfig{
  215. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  216. disableUntunneledUpgrade: true,
  217. useUpstreamProxy: true,
  218. })
  219. }
  220. func TestUnfrontedMeekHTTPSWithUpstreamProxy(t *testing.T) {
  221. controllerRun(t,
  222. &controllerRunConfig{
  223. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  224. disableUntunneledUpgrade: true,
  225. useUpstreamProxy: true,
  226. })
  227. }
  228. func TestObfuscatedSSHFragmentor(t *testing.T) {
  229. controllerRun(t,
  230. &controllerRunConfig{
  231. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  232. disableUntunneledUpgrade: true,
  233. useFragmentor: true,
  234. })
  235. }
  236. func TestFrontedMeekFragmentor(t *testing.T) {
  237. controllerRun(t,
  238. &controllerRunConfig{
  239. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  240. disableUntunneledUpgrade: true,
  241. useFragmentor: true,
  242. })
  243. }
  244. func TestQUIC(t *testing.T) {
  245. if !quic.Enabled() {
  246. t.Skip("QUIC is not enabled")
  247. }
  248. controllerRun(t,
  249. &controllerRunConfig{
  250. protocol: protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH,
  251. disableUntunneledUpgrade: true,
  252. })
  253. }
  254. func TestFrontedQUIC(t *testing.T) {
  255. t.Skipf("temporarily disabled")
  256. if !quic.Enabled() {
  257. t.Skip("QUIC is not enabled")
  258. }
  259. controllerRun(t,
  260. &controllerRunConfig{
  261. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH,
  262. disableUntunneledUpgrade: true,
  263. })
  264. }
  265. func TestInproxyOSSH(t *testing.T) {
  266. if !inproxy.Enabled() {
  267. t.Skip("In-proxy is not enabled")
  268. }
  269. controllerRun(t,
  270. &controllerRunConfig{
  271. protocol: "INPROXY-WEBRTC-OSSH",
  272. disableUntunneledUpgrade: true,
  273. useInproxyDialRateLimit: true,
  274. })
  275. }
  276. func TestInproxyQUICOSSH(t *testing.T) {
  277. if !inproxy.Enabled() {
  278. t.Skip("In-proxy is not enabled")
  279. }
  280. controllerRun(t,
  281. &controllerRunConfig{
  282. protocol: "INPROXY-WEBRTC-QUIC-OSSH",
  283. disableUntunneledUpgrade: true,
  284. useInproxyDialRateLimit: true,
  285. })
  286. }
  287. func TestInproxyUnfrontedMeekHTTPS(t *testing.T) {
  288. if !inproxy.Enabled() {
  289. t.Skip("In-proxy is not enabled")
  290. }
  291. controllerRun(t,
  292. &controllerRunConfig{
  293. protocol: "INPROXY-WEBRTC-UNFRONTED-MEEK-HTTPS-OSSH",
  294. disableUntunneledUpgrade: true,
  295. })
  296. }
  297. func TestInproxyTLSOSSH(t *testing.T) {
  298. if !inproxy.Enabled() {
  299. t.Skip("In-proxy is not enabled")
  300. }
  301. controllerRun(t,
  302. &controllerRunConfig{
  303. protocol: "INPROXY-WEBRTC-TLS-OSSH",
  304. disableUntunneledUpgrade: true,
  305. })
  306. }
  307. func TestTunnelPool(t *testing.T) {
  308. controllerRun(t,
  309. &controllerRunConfig{
  310. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  311. disableUntunneledUpgrade: true,
  312. tunnelPoolSize: 2,
  313. })
  314. }
  315. func TestLegacyAPIEncoding(t *testing.T) {
  316. controllerRun(t,
  317. &controllerRunConfig{
  318. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  319. useLegacyAPIEncoding: true,
  320. })
  321. }
  322. type controllerRunConfig struct {
  323. expectNoServerEntries bool
  324. protocol string
  325. clientIsLatestVersion bool
  326. disableUntunneledUpgrade bool
  327. disableEstablishing bool
  328. disableApi bool
  329. tunnelPoolSize int
  330. useUpstreamProxy bool
  331. disruptNetwork bool
  332. transformHostNames bool
  333. useFragmentor bool
  334. useLegacyAPIEncoding bool
  335. useInproxyDialRateLimit bool
  336. }
  337. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  338. testDataDirName, err := ioutil.TempDir("", "psiphon-controller-test")
  339. if err != nil {
  340. t.Fatalf("TempDir failed: %s\n", err)
  341. }
  342. defer os.RemoveAll(testDataDirName)
  343. configJSON, err := ioutil.ReadFile("controller_test.config")
  344. if err != nil {
  345. // Skip, don't fail, if config file is not present
  346. t.Skipf("error loading configuration file: %s", err)
  347. }
  348. // Note: a successful tactics request may modify config parameters.
  349. var modifyConfig map[string]interface{}
  350. err = json.Unmarshal(configJSON, &modifyConfig)
  351. if err != nil {
  352. t.Fatalf("json.Unmarshal failed: %v", err)
  353. }
  354. modifyConfig["DataRootDirectory"] = testDataDirName
  355. if runConfig.protocol != "" {
  356. modifyConfig["LimitTunnelProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  357. }
  358. modifyConfig["EnableUpgradeDownload"] = true
  359. modifyConfig["EnableFeedbackUpload"] = false
  360. // Override client retry throttle values to speed up automated
  361. // tests and ensure tests complete within fixed deadlines.
  362. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  363. modifyConfig["FetchUpgradeRetryPeriodMilliseconds"] = 250
  364. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  365. if runConfig.disableUntunneledUpgrade {
  366. // Break untunneled upgrade downloader to ensure tunneled case is tested
  367. modifyConfig["UpgradeDownloadClientVersionHeader"] = "invalid-value"
  368. }
  369. if runConfig.transformHostNames {
  370. modifyConfig["TransformHostNames"] = "always"
  371. } else {
  372. modifyConfig["TransformHostNames"] = "never"
  373. }
  374. if runConfig.useFragmentor {
  375. modifyConfig["UseFragmentor"] = "always"
  376. modifyConfig["FragmentorLimitProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  377. modifyConfig["FragmentorMinTotalBytes"] = 1000
  378. modifyConfig["FragmentorMaxTotalBytes"] = 2000
  379. modifyConfig["FragmentorMinWriteBytes"] = 1
  380. modifyConfig["FragmentorMaxWriteBytes"] = 100
  381. modifyConfig["FragmentorMinDelayMicroseconds"] = 1000
  382. modifyConfig["FragmentorMaxDelayMicroseconds"] = 10000
  383. modifyConfig["ObfuscatedSSHMinPadding"] = 4096
  384. modifyConfig["ObfuscatedSSHMaxPadding"] = 8192
  385. }
  386. if runConfig.useLegacyAPIEncoding {
  387. modifyConfig["TargetAPIEncoding"] = protocol.PSIPHON_API_ENCODING_JSON
  388. }
  389. if runConfig.useInproxyDialRateLimit {
  390. modifyConfig["InproxyClientDialRateLimitQuantity"] = 2
  391. modifyConfig["InproxyClientDialRateLimitIntervalMilliseconds"] = 1000
  392. }
  393. configJSON, _ = json.Marshal(modifyConfig)
  394. config, err := LoadConfig(configJSON)
  395. if err != nil {
  396. t.Fatalf("error processing configuration file: %s", err)
  397. }
  398. if config.ClientPlatform == "" {
  399. config.ClientPlatform = testClientPlatform
  400. }
  401. if runConfig.clientIsLatestVersion {
  402. config.ClientVersion = "999999999"
  403. }
  404. if runConfig.disableEstablishing {
  405. // Clear remote server list so tunnel cannot be established.
  406. // TODO: also delete all server entries in the datastore.
  407. config.DisableRemoteServerListFetcher = true
  408. }
  409. if runConfig.disableApi {
  410. config.DisableApi = true
  411. }
  412. config.TunnelPoolSize = runConfig.tunnelPoolSize
  413. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  414. t.Fatalf("cannot use multiple upstream proxies")
  415. }
  416. if runConfig.disruptNetwork {
  417. config.UpstreamProxyURL = disruptorProxyURL
  418. } else if runConfig.useUpstreamProxy {
  419. config.UpstreamProxyURL = upstreamProxyURL
  420. config.CustomHeaders = upstreamProxyCustomHeaders
  421. }
  422. // All config fields should be set before calling Commit.
  423. err = config.Commit(false)
  424. if err != nil {
  425. t.Fatalf("error committing configuration file: %s", err)
  426. }
  427. err = OpenDataStore(config)
  428. if err != nil {
  429. t.Fatalf("error initializing datastore: %s", err)
  430. }
  431. defer CloseDataStore()
  432. serverEntryCount := CountServerEntries()
  433. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  434. // TODO: replace expectNoServerEntries with resetServerEntries
  435. // so tests can run in arbitrary order
  436. t.Fatalf("unexpected server entries")
  437. }
  438. controller, err := NewController(config)
  439. if err != nil {
  440. t.Fatalf("error creating controller: %s", err)
  441. }
  442. // Monitor notices for "Tunnels" with count > 1, the
  443. // indication of tunnel establishment success.
  444. // Also record the selected HTTP proxy port to use
  445. // when fetching websites through the tunnel.
  446. httpProxyPort := 0
  447. tunnelEstablished := make(chan struct{}, 1)
  448. upgradeDownloaded := make(chan struct{}, 1)
  449. remoteServerListDownloaded := make(chan struct{}, 1)
  450. confirmedLatestVersion := make(chan struct{}, 1)
  451. candidateServers := make(chan struct{}, 1)
  452. availableEgressRegions := make(chan struct{}, 1)
  453. var clientUpgradeDownloadedBytesCount int32
  454. var remoteServerListDownloadedBytesCount int32
  455. SetNoticeWriter(NewNoticeReceiver(
  456. func(notice []byte) {
  457. // TODO: log notices without logging server IPs:
  458. //fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  459. noticeType, payload, err := GetNotice(notice)
  460. if err != nil {
  461. return
  462. }
  463. switch noticeType {
  464. case "ListeningHttpProxyPort":
  465. httpProxyPort = int(payload["port"].(float64))
  466. case "ConnectingServer":
  467. serverProtocol := payload["protocol"].(string)
  468. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  469. // TODO: wrong goroutine for t.FatalNow()
  470. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  471. }
  472. case "Tunnels":
  473. count := int(payload["count"].(float64))
  474. if count > 0 {
  475. if runConfig.disableEstablishing {
  476. // TODO: wrong goroutine for t.FatalNow()
  477. t.Fatalf("tunnel established unexpectedly")
  478. } else {
  479. select {
  480. case tunnelEstablished <- struct{}{}:
  481. default:
  482. }
  483. }
  484. }
  485. case "ClientUpgradeDownloadedBytes":
  486. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  487. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  488. case "ClientUpgradeDownloaded":
  489. select {
  490. case upgradeDownloaded <- struct{}{}:
  491. default:
  492. }
  493. case "ClientIsLatestVersion":
  494. select {
  495. case confirmedLatestVersion <- struct{}{}:
  496. default:
  497. }
  498. case "RemoteServerListResourceDownloadedBytes":
  499. url := payload["url"].(string)
  500. if url == config.RemoteServerListUrl {
  501. t.Logf("RemoteServerListResourceDownloadedBytes: %d", int(payload["bytes"].(float64)))
  502. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  503. }
  504. case "RemoteServerListResourceDownloaded":
  505. url := payload["url"].(string)
  506. if url == config.RemoteServerListUrl {
  507. t.Logf("RemoteServerListResourceDownloaded")
  508. select {
  509. case remoteServerListDownloaded <- struct{}{}:
  510. default:
  511. }
  512. }
  513. case "CandidateServers":
  514. select {
  515. case candidateServers <- struct{}{}:
  516. default:
  517. }
  518. case "AvailableEgressRegions":
  519. select {
  520. case availableEgressRegions <- struct{}{}:
  521. default:
  522. }
  523. }
  524. }))
  525. // Run controller, which establishes tunnels
  526. ctx, cancelFunc := context.WithCancel(context.Background())
  527. controllerWaitGroup := new(sync.WaitGroup)
  528. controllerWaitGroup.Add(1)
  529. go func() {
  530. defer controllerWaitGroup.Done()
  531. controller.Run(ctx)
  532. }()
  533. defer func() {
  534. // Test: shutdown must complete within 20 seconds
  535. cancelFunc()
  536. shutdownTimeout := time.NewTimer(20 * time.Second)
  537. shutdownOk := make(chan struct{}, 1)
  538. go func() {
  539. controllerWaitGroup.Wait()
  540. shutdownOk <- struct{}{}
  541. }()
  542. select {
  543. case <-shutdownOk:
  544. case <-shutdownTimeout.C:
  545. t.Fatalf("controller shutdown timeout exceeded")
  546. }
  547. }()
  548. if !runConfig.disableEstablishing {
  549. // Test: tunnel must be established within 120 seconds
  550. establishTimeout := time.NewTimer(120 * time.Second)
  551. select {
  552. case <-tunnelEstablished:
  553. case <-establishTimeout.C:
  554. t.Fatalf("tunnel establish timeout exceeded")
  555. }
  556. // Test: asynchronous server entry scans must complete
  557. select {
  558. case <-candidateServers:
  559. case <-establishTimeout.C:
  560. t.Fatalf("missing candidate servers notice")
  561. }
  562. select {
  563. case <-availableEgressRegions:
  564. case <-establishTimeout.C:
  565. t.Fatalf("missing available egress regions notice")
  566. }
  567. // Test: if starting with no server entries, a fetch remote
  568. // server list must have succeeded. With disruptNetwork, the
  569. // fetch must have been resumed at least once.
  570. if serverEntryCount == 0 {
  571. select {
  572. case <-remoteServerListDownloaded:
  573. default:
  574. t.Fatalf("expected remote server list downloaded")
  575. }
  576. if runConfig.disruptNetwork {
  577. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  578. if count <= 1 {
  579. t.Fatalf("unexpected remote server list download progress: %d", count)
  580. }
  581. }
  582. }
  583. // Cannot establish port forwards in DisableApi mode
  584. if !runConfig.disableApi {
  585. // Test: fetch website through tunnel
  586. // Allow for known race condition described in NewHttpProxy():
  587. time.Sleep(1 * time.Second)
  588. if !runConfig.disruptNetwork {
  589. fetchAndVerifyWebsite(t, httpProxyPort)
  590. }
  591. }
  592. }
  593. // Test: upgrade check/download must be downloaded within 240 seconds
  594. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  595. if expectUpgrade {
  596. upgradeTimeout := time.NewTimer(240 * time.Second)
  597. select {
  598. case <-upgradeDownloaded:
  599. // TODO: verify downloaded file
  600. if runConfig.clientIsLatestVersion {
  601. t.Fatalf("upgrade downloaded unexpectedly")
  602. }
  603. // Test: with disruptNetwork, must be multiple download progress notices
  604. if runConfig.disruptNetwork {
  605. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  606. if count <= 1 {
  607. t.Fatalf("unexpected upgrade download progress: %d", count)
  608. }
  609. }
  610. case <-confirmedLatestVersion:
  611. if !runConfig.clientIsLatestVersion {
  612. t.Fatalf("confirmed latest version unexpectedly")
  613. }
  614. case <-upgradeTimeout.C:
  615. t.Fatalf("upgrade download timeout exceeded")
  616. }
  617. }
  618. }
  619. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  620. testUrl := "https://psiphon.ca"
  621. roundTripTimeout := 30 * time.Second
  622. expectedResponseContains := "Psiphon"
  623. checkResponse := func(responseBody string) bool {
  624. return strings.Contains(responseBody, expectedResponseContains)
  625. }
  626. // Retries are made to compensate for intermittent failures due
  627. // to external network conditions.
  628. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  629. retryCount := 6
  630. retryDelay := 5 * time.Second
  631. var err error
  632. for i := 0; i < retryCount; i++ {
  633. err = fetchFunc()
  634. if err == nil || i == retryCount-1 {
  635. break
  636. }
  637. time.Sleep(retryDelay)
  638. t.Logf("retrying %s...", fetchName)
  639. }
  640. return err
  641. }
  642. // Test: use HTTP proxy
  643. fetchUsingHTTPProxy := func() error {
  644. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  645. if err != nil {
  646. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  647. }
  648. httpTransport := &http.Transport{
  649. Proxy: http.ProxyURL(proxyUrl),
  650. DisableKeepAlives: true,
  651. }
  652. httpClient := &http.Client{
  653. Transport: httpTransport,
  654. Timeout: roundTripTimeout,
  655. }
  656. request, err := http.NewRequest("GET", testUrl, nil)
  657. if err != nil {
  658. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  659. }
  660. response, err := httpClient.Do(request)
  661. if err != nil {
  662. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  663. }
  664. defer response.Body.Close()
  665. body, err := ioutil.ReadAll(response.Body)
  666. if err != nil {
  667. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  668. }
  669. if !checkResponse(string(body)) {
  670. return fmt.Errorf("unexpected proxied HTTP response")
  671. }
  672. return nil
  673. }
  674. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  675. if err != nil {
  676. return err
  677. }
  678. // Delay before requesting from external service again
  679. time.Sleep(1 * time.Second)
  680. // Test: use direct URL proxy
  681. fetchUsingURLProxyDirect := func() error {
  682. httpTransport := &http.Transport{
  683. DisableKeepAlives: true,
  684. }
  685. httpClient := &http.Client{
  686. Transport: httpTransport,
  687. Timeout: roundTripTimeout,
  688. }
  689. request, err := http.NewRequest(
  690. "GET",
  691. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  692. httpProxyPort, url.QueryEscape(testUrl)),
  693. nil)
  694. if err != nil {
  695. return fmt.Errorf("error preparing direct URL request: %s", err)
  696. }
  697. response, err := httpClient.Do(request)
  698. if err != nil {
  699. return fmt.Errorf("error sending direct URL request: %s", err)
  700. }
  701. defer response.Body.Close()
  702. body, err := ioutil.ReadAll(response.Body)
  703. if err != nil {
  704. return fmt.Errorf("error reading direct URL response: %s", err)
  705. }
  706. if !checkResponse(string(body)) {
  707. return fmt.Errorf("unexpected direct URL response")
  708. }
  709. return nil
  710. }
  711. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  712. if err != nil {
  713. return err
  714. }
  715. // Delay before requesting from external service again
  716. time.Sleep(1 * time.Second)
  717. // Test: use tunneled URL proxy
  718. fetchUsingURLProxyTunneled := func() error {
  719. httpTransport := &http.Transport{
  720. DisableKeepAlives: true,
  721. }
  722. httpClient := &http.Client{
  723. Transport: httpTransport,
  724. Timeout: roundTripTimeout,
  725. }
  726. request, err := http.NewRequest(
  727. "GET",
  728. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  729. httpProxyPort, url.QueryEscape(testUrl)),
  730. nil)
  731. if err != nil {
  732. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  733. }
  734. response, err := httpClient.Do(request)
  735. if err != nil {
  736. return fmt.Errorf("error sending tunneled URL request: %s", err)
  737. }
  738. defer response.Body.Close()
  739. body, err := ioutil.ReadAll(response.Body)
  740. if err != nil {
  741. return fmt.Errorf("error reading tunneled URL response: %s", err)
  742. }
  743. if !checkResponse(string(body)) {
  744. return fmt.Errorf("unexpected tunneled URL response")
  745. }
  746. return nil
  747. }
  748. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  749. if err != nil {
  750. return err
  751. }
  752. return nil
  753. }
  754. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  755. // network; for example, the size of the remote server list resource must exceed
  756. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  757. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  758. // too small, the test will take longer to run since more retries are necessary.
  759. //
  760. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  761. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  762. // these test in controller_test serve the dual purpose of ensuring that tunnel
  763. // core works with the production network.
  764. //
  765. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  766. // based on current production network configuration?
  767. const disruptorProxyAddress = "127.0.0.1:2160"
  768. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  769. const disruptorMaxConnectionBytes = 150000
  770. const disruptorMaxConnectionTime = 10 * time.Second
  771. func initDisruptor() {
  772. go func() {
  773. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  774. if err != nil {
  775. fmt.Printf("disruptor proxy listen error: %s\n", err)
  776. return
  777. }
  778. for {
  779. localConn, err := listener.AcceptSocks()
  780. if err != nil {
  781. if e, ok := err.(net.Error); ok && e.Temporary() {
  782. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  783. continue
  784. }
  785. fmt.Printf("disruptor proxy accept error: %s\n", err)
  786. return
  787. }
  788. go func() {
  789. defer localConn.Close()
  790. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  791. if err != nil {
  792. // TODO: log "err" without logging server IPs
  793. fmt.Printf("disruptor proxy dial error\n")
  794. return
  795. }
  796. defer remoteConn.Close()
  797. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  798. if err != nil {
  799. fmt.Printf("disruptor proxy grant error: %s\n", err)
  800. return
  801. }
  802. // Cut connection after disruptorMaxConnectionTime
  803. time.AfterFunc(disruptorMaxConnectionTime, func() {
  804. localConn.Close()
  805. remoteConn.Close()
  806. })
  807. // Relay connection, but only up to disruptorMaxConnectionBytes
  808. waitGroup := new(sync.WaitGroup)
  809. waitGroup.Add(1)
  810. go func() {
  811. defer waitGroup.Done()
  812. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  813. localConn.Close()
  814. remoteConn.Close()
  815. }()
  816. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  817. localConn.Close()
  818. remoteConn.Close()
  819. waitGroup.Wait()
  820. }()
  821. }
  822. }()
  823. }
  824. const upstreamProxyURL = "http://testUser:testPassword@127.0.0.1:2161"
  825. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  826. func hasExpectedCustomHeaders(h http.Header) bool {
  827. for name, values := range upstreamProxyCustomHeaders {
  828. if h[name] == nil {
  829. return false
  830. }
  831. // Order may not be the same
  832. for _, value := range values {
  833. if !common.Contains(h[name], value) {
  834. return false
  835. }
  836. }
  837. }
  838. return true
  839. }
  840. func initUpstreamProxy() {
  841. go func() {
  842. proxy := goproxy.NewProxyHttpServer()
  843. proxy.Logger = log.New(ioutil.Discard, "", 0)
  844. auth.ProxyBasic(
  845. proxy,
  846. "testRealm",
  847. func(user, passwd string) bool { return user == "testUser" && passwd == "testPassword" })
  848. proxy.OnRequest().DoFunc(
  849. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  850. if !hasExpectedCustomHeaders(r.Header) {
  851. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  852. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  853. }
  854. return r, nil
  855. })
  856. proxy.OnRequest().HandleConnectFunc(
  857. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  858. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  859. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  860. return goproxy.RejectConnect, host
  861. }
  862. return goproxy.OkConnect, host
  863. })
  864. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  865. if err != nil {
  866. fmt.Printf("upstream proxy failed: %s\n", err)
  867. }
  868. }()
  869. // TODO: wait until listener is active?
  870. }