controller_test.go 30 KB

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