controller_test.go 28 KB

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