controller_test.go 30 KB

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