controller_test.go 27 KB

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