controller_test.go 30 KB

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