controller_test.go 31 KB

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