controller_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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/protocol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  41. "github.com/elazarl/goproxy"
  42. )
  43. func TestMain(m *testing.M) {
  44. flag.Parse()
  45. SetEmitDiagnosticNotices(true, 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. if !quic.Enabled() {
  395. t.Skip("QUIC is not enabled")
  396. }
  397. controllerRun(t,
  398. &controllerRunConfig{
  399. expectNoServerEntries: false,
  400. protocol: protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH,
  401. clientIsLatestVersion: false,
  402. disableUntunneledUpgrade: true,
  403. disableEstablishing: false,
  404. disableApi: false,
  405. tunnelPoolSize: 1,
  406. useUpstreamProxy: false,
  407. disruptNetwork: false,
  408. transformHostNames: false,
  409. useFragmentor: false,
  410. })
  411. }
  412. func TestFrontedQUIC(t *testing.T) {
  413. if !quic.Enabled() {
  414. t.Skip("QUIC is not enabled")
  415. }
  416. controllerRun(t,
  417. &controllerRunConfig{
  418. expectNoServerEntries: false,
  419. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH,
  420. clientIsLatestVersion: false,
  421. disableUntunneledUpgrade: true,
  422. disableEstablishing: false,
  423. disableApi: false,
  424. tunnelPoolSize: 1,
  425. useUpstreamProxy: false,
  426. disruptNetwork: false,
  427. transformHostNames: false,
  428. useFragmentor: false,
  429. })
  430. }
  431. type controllerRunConfig struct {
  432. expectNoServerEntries bool
  433. protocol string
  434. clientIsLatestVersion bool
  435. disableUntunneledUpgrade bool
  436. disableEstablishing bool
  437. disableApi bool
  438. tunnelPoolSize int
  439. useUpstreamProxy bool
  440. disruptNetwork bool
  441. transformHostNames bool
  442. useFragmentor bool
  443. }
  444. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  445. testDataDirName, err := ioutil.TempDir("", "psiphon-controller-test")
  446. if err != nil {
  447. t.Fatalf("TempDir failed: %s\n", err)
  448. }
  449. defer os.RemoveAll(testDataDirName)
  450. configJSON, err := ioutil.ReadFile("controller_test.config")
  451. if err != nil {
  452. // Skip, don't fail, if config file is not present
  453. t.Skipf("error loading configuration file: %s", err)
  454. }
  455. // Note: a successful tactics request may modify config parameters.
  456. var modifyConfig map[string]interface{}
  457. json.Unmarshal(configJSON, &modifyConfig)
  458. modifyConfig["DataRootDirectory"] = testDataDirName
  459. if runConfig.protocol != "" {
  460. modifyConfig["LimitTunnelProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  461. }
  462. // Override client retry throttle values to speed up automated
  463. // tests and ensure tests complete within fixed deadlines.
  464. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  465. modifyConfig["FetchUpgradeRetryPeriodMilliseconds"] = 250
  466. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  467. if runConfig.disableUntunneledUpgrade {
  468. // Disable untunneled upgrade downloader to ensure tunneled case is tested
  469. modifyConfig["UpgradeDownloadClientVersionHeader"] = "invalid-value"
  470. }
  471. if runConfig.transformHostNames {
  472. modifyConfig["TransformHostNames"] = "always"
  473. } else {
  474. modifyConfig["TransformHostNames"] = "never"
  475. }
  476. if runConfig.useFragmentor {
  477. modifyConfig["UseFragmentor"] = "always"
  478. modifyConfig["FragmentorLimitProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  479. modifyConfig["FragmentorMinTotalBytes"] = 1000
  480. modifyConfig["FragmentorMaxTotalBytes"] = 2000
  481. modifyConfig["FragmentorMinWriteBytes"] = 1
  482. modifyConfig["FragmentorMaxWriteBytes"] = 100
  483. modifyConfig["FragmentorMinDelayMicroseconds"] = 1000
  484. modifyConfig["FragmentorMaxDelayMicroseconds"] = 10000
  485. modifyConfig["ObfuscatedSSHMinPadding"] = 4096
  486. modifyConfig["ObfuscatedSSHMaxPadding"] = 8192
  487. }
  488. configJSON, _ = json.Marshal(modifyConfig)
  489. config, err := LoadConfig(configJSON)
  490. if err != nil {
  491. t.Fatalf("error processing configuration file: %s", err)
  492. }
  493. if runConfig.clientIsLatestVersion {
  494. config.ClientVersion = "999999999"
  495. }
  496. if runConfig.disableEstablishing {
  497. // Clear remote server list so tunnel cannot be established.
  498. // TODO: also delete all server entries in the datastore.
  499. config.DisableRemoteServerListFetcher = true
  500. }
  501. if runConfig.disableApi {
  502. config.DisableApi = true
  503. }
  504. config.TunnelPoolSize = runConfig.tunnelPoolSize
  505. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  506. t.Fatalf("cannot use multiple upstream proxies")
  507. }
  508. if runConfig.disruptNetwork {
  509. config.UpstreamProxyURL = disruptorProxyURL
  510. } else if runConfig.useUpstreamProxy {
  511. config.UpstreamProxyURL = upstreamProxyURL
  512. config.CustomHeaders = upstreamProxyCustomHeaders
  513. }
  514. // All config fields should be set before calling Commit.
  515. err = config.Commit(false)
  516. if err != nil {
  517. t.Fatalf("error committing configuration file: %s", err)
  518. }
  519. // Enable tactics requests. This will passively exercise the code
  520. // paths. server_test runs a more comprehensive test that checks
  521. // that the tactics request succeeds.
  522. config.NetworkID = "NETWORK1"
  523. err = OpenDataStore(config)
  524. if err != nil {
  525. t.Fatalf("error initializing datastore: %s", err)
  526. }
  527. defer CloseDataStore()
  528. serverEntryCount := CountServerEntries()
  529. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  530. // TODO: replace expectNoServerEntries with resetServerEntries
  531. // so tests can run in arbitrary order
  532. t.Fatalf("unexpected server entries")
  533. }
  534. controller, err := NewController(config)
  535. if err != nil {
  536. t.Fatalf("error creating controller: %s", err)
  537. }
  538. // Monitor notices for "Tunnels" with count > 1, the
  539. // indication of tunnel establishment success.
  540. // Also record the selected HTTP proxy port to use
  541. // when fetching websites through the tunnel.
  542. httpProxyPort := 0
  543. tunnelEstablished := make(chan struct{}, 1)
  544. upgradeDownloaded := make(chan struct{}, 1)
  545. remoteServerListDownloaded := make(chan struct{}, 1)
  546. confirmedLatestVersion := make(chan struct{}, 1)
  547. var clientUpgradeDownloadedBytesCount int32
  548. var remoteServerListDownloadedBytesCount int32
  549. SetNoticeWriter(NewNoticeReceiver(
  550. func(notice []byte) {
  551. // TODO: log notices without logging server IPs:
  552. //fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  553. noticeType, payload, err := GetNotice(notice)
  554. if err != nil {
  555. return
  556. }
  557. switch noticeType {
  558. case "ListeningHttpProxyPort":
  559. httpProxyPort = int(payload["port"].(float64))
  560. case "ConnectingServer":
  561. serverProtocol := payload["protocol"].(string)
  562. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  563. // TODO: wrong goroutine for t.FatalNow()
  564. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  565. }
  566. case "Tunnels":
  567. count := int(payload["count"].(float64))
  568. if count > 0 {
  569. if runConfig.disableEstablishing {
  570. // TODO: wrong goroutine for t.FatalNow()
  571. t.Fatalf("tunnel established unexpectedly")
  572. } else {
  573. select {
  574. case tunnelEstablished <- struct{}{}:
  575. default:
  576. }
  577. }
  578. }
  579. case "ClientUpgradeDownloadedBytes":
  580. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  581. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  582. case "ClientUpgradeDownloaded":
  583. select {
  584. case upgradeDownloaded <- struct{}{}:
  585. default:
  586. }
  587. case "ClientIsLatestVersion":
  588. select {
  589. case confirmedLatestVersion <- struct{}{}:
  590. default:
  591. }
  592. case "RemoteServerListResourceDownloadedBytes":
  593. url := payload["url"].(string)
  594. if url == config.RemoteServerListUrl {
  595. t.Logf("RemoteServerListResourceDownloadedBytes: %d", int(payload["bytes"].(float64)))
  596. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  597. }
  598. case "RemoteServerListResourceDownloaded":
  599. url := payload["url"].(string)
  600. if url == config.RemoteServerListUrl {
  601. t.Logf("RemoteServerListResourceDownloaded")
  602. select {
  603. case remoteServerListDownloaded <- struct{}{}:
  604. default:
  605. }
  606. }
  607. }
  608. }))
  609. // Run controller, which establishes tunnels
  610. ctx, cancelFunc := context.WithCancel(context.Background())
  611. controllerWaitGroup := new(sync.WaitGroup)
  612. controllerWaitGroup.Add(1)
  613. go func() {
  614. defer controllerWaitGroup.Done()
  615. controller.Run(ctx)
  616. }()
  617. defer func() {
  618. // Test: shutdown must complete within 20 seconds
  619. cancelFunc()
  620. shutdownTimeout := time.NewTimer(20 * time.Second)
  621. shutdownOk := make(chan struct{}, 1)
  622. go func() {
  623. controllerWaitGroup.Wait()
  624. shutdownOk <- struct{}{}
  625. }()
  626. select {
  627. case <-shutdownOk:
  628. case <-shutdownTimeout.C:
  629. t.Fatalf("controller shutdown timeout exceeded")
  630. }
  631. }()
  632. if !runConfig.disableEstablishing {
  633. // Test: tunnel must be established within 120 seconds
  634. establishTimeout := time.NewTimer(120 * time.Second)
  635. select {
  636. case <-tunnelEstablished:
  637. case <-establishTimeout.C:
  638. t.Fatalf("tunnel establish timeout exceeded")
  639. }
  640. // Test: if starting with no server entries, a fetch remote
  641. // server list must have succeeded. With disruptNetwork, the
  642. // fetch must have been resumed at least once.
  643. if serverEntryCount == 0 {
  644. select {
  645. case <-remoteServerListDownloaded:
  646. default:
  647. t.Fatalf("expected remote server list downloaded")
  648. }
  649. if runConfig.disruptNetwork {
  650. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  651. if count <= 1 {
  652. t.Fatalf("unexpected remote server list download progress: %d", count)
  653. }
  654. }
  655. }
  656. // Cannot establish port forwards in DisableApi mode
  657. if !runConfig.disableApi {
  658. // Test: fetch website through tunnel
  659. // Allow for known race condition described in NewHttpProxy():
  660. time.Sleep(1 * time.Second)
  661. if !runConfig.disruptNetwork {
  662. fetchAndVerifyWebsite(t, httpProxyPort)
  663. }
  664. }
  665. }
  666. // Test: upgrade check/download must be downloaded within 180 seconds
  667. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  668. if expectUpgrade {
  669. upgradeTimeout := time.NewTimer(120 * time.Second)
  670. select {
  671. case <-upgradeDownloaded:
  672. // TODO: verify downloaded file
  673. if runConfig.clientIsLatestVersion {
  674. t.Fatalf("upgrade downloaded unexpectedly")
  675. }
  676. // Test: with disruptNetwork, must be multiple download progress notices
  677. if runConfig.disruptNetwork {
  678. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  679. if count <= 1 {
  680. t.Fatalf("unexpected upgrade download progress: %d", count)
  681. }
  682. }
  683. case <-confirmedLatestVersion:
  684. if !runConfig.clientIsLatestVersion {
  685. t.Fatalf("confirmed latest version unexpectedly")
  686. }
  687. case <-upgradeTimeout.C:
  688. t.Fatalf("upgrade download timeout exceeded")
  689. }
  690. }
  691. }
  692. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  693. testUrl := "https://psiphon.ca"
  694. roundTripTimeout := 30 * time.Second
  695. expectedResponseContains := "Psiphon"
  696. checkResponse := func(responseBody string) bool {
  697. return strings.Contains(responseBody, expectedResponseContains)
  698. }
  699. // Retries are made to compensate for intermittent failures due
  700. // to external network conditions.
  701. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  702. retryCount := 6
  703. retryDelay := 5 * time.Second
  704. var err error
  705. for i := 0; i < retryCount; i++ {
  706. err = fetchFunc()
  707. if err == nil || i == retryCount-1 {
  708. break
  709. }
  710. time.Sleep(retryDelay)
  711. t.Logf("retrying %s...", fetchName)
  712. }
  713. return err
  714. }
  715. // Test: use HTTP proxy
  716. fetchUsingHTTPProxy := func() error {
  717. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  718. if err != nil {
  719. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  720. }
  721. httpTransport := &http.Transport{
  722. Proxy: http.ProxyURL(proxyUrl),
  723. DisableKeepAlives: true,
  724. }
  725. httpClient := &http.Client{
  726. Transport: httpTransport,
  727. Timeout: roundTripTimeout,
  728. }
  729. request, err := http.NewRequest("GET", testUrl, nil)
  730. if err != nil {
  731. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  732. }
  733. response, err := httpClient.Do(request)
  734. if err != nil {
  735. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  736. }
  737. defer response.Body.Close()
  738. body, err := ioutil.ReadAll(response.Body)
  739. if err != nil {
  740. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  741. }
  742. if !checkResponse(string(body)) {
  743. return fmt.Errorf("unexpected proxied HTTP response")
  744. }
  745. return nil
  746. }
  747. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  748. if err != nil {
  749. return err
  750. }
  751. // Delay before requesting from external service again
  752. time.Sleep(1 * time.Second)
  753. // Test: use direct URL proxy
  754. fetchUsingURLProxyDirect := func() error {
  755. httpTransport := &http.Transport{
  756. DisableKeepAlives: true,
  757. }
  758. httpClient := &http.Client{
  759. Transport: httpTransport,
  760. Timeout: roundTripTimeout,
  761. }
  762. request, err := http.NewRequest(
  763. "GET",
  764. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  765. httpProxyPort, url.QueryEscape(testUrl)),
  766. nil)
  767. if err != nil {
  768. return fmt.Errorf("error preparing direct URL request: %s", err)
  769. }
  770. response, err := httpClient.Do(request)
  771. if err != nil {
  772. return fmt.Errorf("error sending direct URL request: %s", err)
  773. }
  774. defer response.Body.Close()
  775. body, err := ioutil.ReadAll(response.Body)
  776. if err != nil {
  777. return fmt.Errorf("error reading direct URL response: %s", err)
  778. }
  779. if !checkResponse(string(body)) {
  780. return fmt.Errorf("unexpected direct URL response")
  781. }
  782. return nil
  783. }
  784. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  785. if err != nil {
  786. return err
  787. }
  788. // Delay before requesting from external service again
  789. time.Sleep(1 * time.Second)
  790. // Test: use tunneled URL proxy
  791. fetchUsingURLProxyTunneled := func() error {
  792. httpTransport := &http.Transport{
  793. DisableKeepAlives: true,
  794. }
  795. httpClient := &http.Client{
  796. Transport: httpTransport,
  797. Timeout: roundTripTimeout,
  798. }
  799. request, err := http.NewRequest(
  800. "GET",
  801. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  802. httpProxyPort, url.QueryEscape(testUrl)),
  803. nil)
  804. if err != nil {
  805. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  806. }
  807. response, err := httpClient.Do(request)
  808. if err != nil {
  809. return fmt.Errorf("error sending tunneled URL request: %s", err)
  810. }
  811. defer response.Body.Close()
  812. body, err := ioutil.ReadAll(response.Body)
  813. if err != nil {
  814. return fmt.Errorf("error reading tunneled URL response: %s", err)
  815. }
  816. if !checkResponse(string(body)) {
  817. return fmt.Errorf("unexpected tunneled URL response")
  818. }
  819. return nil
  820. }
  821. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  822. if err != nil {
  823. return err
  824. }
  825. return nil
  826. }
  827. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  828. // network; for example, the size of the remote server list resource must exceed
  829. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  830. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  831. // too small, the test will take longer to run since more retries are necessary.
  832. //
  833. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  834. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  835. // these test in controller_test serve the dual purpose of ensuring that tunnel
  836. // core works with the production network.
  837. //
  838. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  839. // based on current production network configuration?
  840. const disruptorProxyAddress = "127.0.0.1:2160"
  841. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  842. const disruptorMaxConnectionBytes = 250000
  843. const disruptorMaxConnectionTime = 10 * time.Second
  844. func initDisruptor() {
  845. go func() {
  846. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  847. if err != nil {
  848. fmt.Printf("disruptor proxy listen error: %s\n", err)
  849. return
  850. }
  851. for {
  852. localConn, err := listener.AcceptSocks()
  853. if err != nil {
  854. if e, ok := err.(net.Error); ok && e.Temporary() {
  855. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  856. continue
  857. }
  858. fmt.Printf("disruptor proxy accept error: %s\n", err)
  859. return
  860. }
  861. go func() {
  862. defer localConn.Close()
  863. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  864. if err != nil {
  865. // TODO: log "err" without logging server IPs
  866. fmt.Printf("disruptor proxy dial error\n")
  867. return
  868. }
  869. defer remoteConn.Close()
  870. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  871. if err != nil {
  872. fmt.Printf("disruptor proxy grant error: %s\n", err)
  873. return
  874. }
  875. // Cut connection after disruptorMaxConnectionTime
  876. time.AfterFunc(disruptorMaxConnectionTime, func() {
  877. localConn.Close()
  878. remoteConn.Close()
  879. })
  880. // Relay connection, but only up to disruptorMaxConnectionBytes
  881. waitGroup := new(sync.WaitGroup)
  882. waitGroup.Add(1)
  883. go func() {
  884. defer waitGroup.Done()
  885. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  886. localConn.Close()
  887. remoteConn.Close()
  888. }()
  889. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  890. localConn.Close()
  891. remoteConn.Close()
  892. waitGroup.Wait()
  893. }()
  894. }
  895. }()
  896. }
  897. const upstreamProxyURL = "http://127.0.0.1:2161"
  898. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  899. func hasExpectedCustomHeaders(h http.Header) bool {
  900. for name, values := range upstreamProxyCustomHeaders {
  901. if h[name] == nil {
  902. return false
  903. }
  904. // Order may not be the same
  905. for _, value := range values {
  906. if !common.Contains(h[name], value) {
  907. return false
  908. }
  909. }
  910. }
  911. return true
  912. }
  913. func initUpstreamProxy() {
  914. go func() {
  915. proxy := goproxy.NewProxyHttpServer()
  916. proxy.Logger = log.New(ioutil.Discard, "", 0)
  917. proxy.OnRequest().DoFunc(
  918. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  919. if !hasExpectedCustomHeaders(r.Header) {
  920. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  921. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  922. }
  923. return r, nil
  924. })
  925. proxy.OnRequest().HandleConnectFunc(
  926. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  927. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  928. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  929. return goproxy.RejectConnect, host
  930. }
  931. return goproxy.OkConnect, host
  932. })
  933. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  934. if err != nil {
  935. fmt.Printf("upstream proxy failed: %s\n", err)
  936. }
  937. }()
  938. // TODO: wait until listener is active?
  939. }