controller_test.go 32 KB

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