controller_test.go 30 KB

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