controller_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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. "flag"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "os"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "testing"
  33. "time"
  34. "github.com/Psiphon-Inc/goarista/monotime"
  35. socks "github.com/Psiphon-Inc/goptlib"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  37. "github.com/elazarl/goproxy"
  38. )
  39. func TestMain(m *testing.M) {
  40. flag.Parse()
  41. os.Remove(DATA_STORE_FILENAME)
  42. initDisruptor()
  43. initUpstreamProxy()
  44. SetEmitDiagnosticNotices(true)
  45. os.Exit(m.Run())
  46. }
  47. // Test case notes/limitations/dependencies:
  48. //
  49. // * Untunneled upgrade tests must execute before
  50. // the other tests to ensure no tunnel is established.
  51. // We need a way to reset the datastore after it's been
  52. // initialized in order to to clear out its data entries
  53. // and be able to arbitrarily order the tests.
  54. //
  55. // * The resumable download tests using disruptNetwork
  56. // depend on the download object being larger than the
  57. // disruptorMax limits so that the disruptor will actually
  58. // interrupt the first download attempt. Specifically, the
  59. // upgrade and remote server list at the URLs specified in
  60. // controller_test.config.enc.
  61. //
  62. // * The protocol tests assume there is at least one server
  63. // supporting each protocol in the server list at the URL
  64. // specified in controller_test.config.enc, and that these
  65. // servers are not overloaded.
  66. //
  67. // * fetchAndVerifyWebsite depends on the target URL being
  68. // available and responding.
  69. //
  70. func TestUntunneledUpgradeDownload(t *testing.T) {
  71. controllerRun(t,
  72. &controllerRunConfig{
  73. expectNoServerEntries: true,
  74. protocol: "",
  75. clientIsLatestVersion: false,
  76. disableUntunneledUpgrade: false,
  77. disableEstablishing: true,
  78. disableApi: false,
  79. tunnelPoolSize: 1,
  80. useUpstreamProxy: false,
  81. disruptNetwork: false,
  82. useHostNameTransformer: false,
  83. runDuration: 0,
  84. })
  85. }
  86. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  87. controllerRun(t,
  88. &controllerRunConfig{
  89. expectNoServerEntries: true,
  90. protocol: "",
  91. clientIsLatestVersion: false,
  92. disableUntunneledUpgrade: false,
  93. disableEstablishing: true,
  94. disableApi: false,
  95. tunnelPoolSize: 1,
  96. useUpstreamProxy: false,
  97. disruptNetwork: true,
  98. useHostNameTransformer: false,
  99. runDuration: 0,
  100. })
  101. }
  102. func TestUntunneledUpgradeClientIsLatestVersion(t *testing.T) {
  103. controllerRun(t,
  104. &controllerRunConfig{
  105. expectNoServerEntries: true,
  106. protocol: "",
  107. clientIsLatestVersion: true,
  108. disableUntunneledUpgrade: false,
  109. disableEstablishing: true,
  110. disableApi: false,
  111. tunnelPoolSize: 1,
  112. useUpstreamProxy: false,
  113. disruptNetwork: false,
  114. useHostNameTransformer: false,
  115. runDuration: 0,
  116. })
  117. }
  118. func TestUntunneledResumableFetchRemoveServerList(t *testing.T) {
  119. controllerRun(t,
  120. &controllerRunConfig{
  121. expectNoServerEntries: true,
  122. protocol: "",
  123. clientIsLatestVersion: true,
  124. disableUntunneledUpgrade: false,
  125. disableEstablishing: false,
  126. disableApi: false,
  127. tunnelPoolSize: 1,
  128. useUpstreamProxy: false,
  129. disruptNetwork: true,
  130. useHostNameTransformer: false,
  131. runDuration: 0,
  132. })
  133. }
  134. func TestTunneledUpgradeClientIsLatestVersion(t *testing.T) {
  135. controllerRun(t,
  136. &controllerRunConfig{
  137. expectNoServerEntries: false,
  138. protocol: "",
  139. clientIsLatestVersion: true,
  140. disableUntunneledUpgrade: true,
  141. disableEstablishing: false,
  142. disableApi: false,
  143. tunnelPoolSize: 1,
  144. useUpstreamProxy: false,
  145. disruptNetwork: false,
  146. useHostNameTransformer: false,
  147. runDuration: 0,
  148. })
  149. }
  150. func TestImpairedProtocols(t *testing.T) {
  151. // This test sets a tunnelPoolSize of 40 and runs
  152. // the session for 1 minute with network disruption
  153. // on. All 40 tunnels being disrupted every 10
  154. // seconds (followed by ssh keep alive probe timeout)
  155. // should be sufficient to trigger at least one
  156. // impaired protocol classification.
  157. controllerRun(t,
  158. &controllerRunConfig{
  159. expectNoServerEntries: false,
  160. protocol: "",
  161. clientIsLatestVersion: true,
  162. disableUntunneledUpgrade: true,
  163. disableEstablishing: false,
  164. disableApi: false,
  165. tunnelPoolSize: 40,
  166. useUpstreamProxy: false,
  167. disruptNetwork: true,
  168. useHostNameTransformer: false,
  169. runDuration: 1 * time.Minute,
  170. })
  171. }
  172. func TestSSH(t *testing.T) {
  173. controllerRun(t,
  174. &controllerRunConfig{
  175. expectNoServerEntries: false,
  176. protocol: common.TUNNEL_PROTOCOL_SSH,
  177. clientIsLatestVersion: false,
  178. disableUntunneledUpgrade: true,
  179. disableEstablishing: false,
  180. disableApi: false,
  181. tunnelPoolSize: 1,
  182. useUpstreamProxy: false,
  183. disruptNetwork: false,
  184. useHostNameTransformer: false,
  185. runDuration: 0,
  186. })
  187. }
  188. func TestObfuscatedSSH(t *testing.T) {
  189. controllerRun(t,
  190. &controllerRunConfig{
  191. expectNoServerEntries: false,
  192. protocol: common.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  193. clientIsLatestVersion: false,
  194. disableUntunneledUpgrade: true,
  195. disableEstablishing: false,
  196. disableApi: false,
  197. tunnelPoolSize: 1,
  198. useUpstreamProxy: false,
  199. disruptNetwork: false,
  200. useHostNameTransformer: false,
  201. runDuration: 0,
  202. })
  203. }
  204. func TestUnfrontedMeek(t *testing.T) {
  205. controllerRun(t,
  206. &controllerRunConfig{
  207. expectNoServerEntries: false,
  208. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  209. clientIsLatestVersion: false,
  210. disableUntunneledUpgrade: true,
  211. disableEstablishing: false,
  212. disableApi: false,
  213. tunnelPoolSize: 1,
  214. useUpstreamProxy: false,
  215. disruptNetwork: false,
  216. useHostNameTransformer: false,
  217. runDuration: 0,
  218. })
  219. }
  220. func TestUnfrontedMeekWithTransformer(t *testing.T) {
  221. controllerRun(t,
  222. &controllerRunConfig{
  223. expectNoServerEntries: false,
  224. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  225. clientIsLatestVersion: true,
  226. disableUntunneledUpgrade: true,
  227. disableEstablishing: false,
  228. disableApi: false,
  229. tunnelPoolSize: 1,
  230. useUpstreamProxy: false,
  231. disruptNetwork: false,
  232. useHostNameTransformer: true,
  233. runDuration: 0,
  234. })
  235. }
  236. func TestFrontedMeek(t *testing.T) {
  237. controllerRun(t,
  238. &controllerRunConfig{
  239. expectNoServerEntries: false,
  240. protocol: common.TUNNEL_PROTOCOL_FRONTED_MEEK,
  241. clientIsLatestVersion: false,
  242. disableUntunneledUpgrade: true,
  243. disableEstablishing: false,
  244. disableApi: false,
  245. tunnelPoolSize: 1,
  246. useUpstreamProxy: false,
  247. disruptNetwork: false,
  248. useHostNameTransformer: false,
  249. runDuration: 0,
  250. })
  251. }
  252. func TestFrontedMeekWithTransformer(t *testing.T) {
  253. controllerRun(t,
  254. &controllerRunConfig{
  255. expectNoServerEntries: false,
  256. protocol: common.TUNNEL_PROTOCOL_FRONTED_MEEK,
  257. clientIsLatestVersion: true,
  258. disableUntunneledUpgrade: true,
  259. disableEstablishing: false,
  260. disableApi: false,
  261. tunnelPoolSize: 1,
  262. useUpstreamProxy: false,
  263. disruptNetwork: false,
  264. useHostNameTransformer: true,
  265. runDuration: 0,
  266. })
  267. }
  268. func TestFrontedMeekHTTP(t *testing.T) {
  269. controllerRun(t,
  270. &controllerRunConfig{
  271. expectNoServerEntries: false,
  272. protocol: common.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP,
  273. clientIsLatestVersion: true,
  274. disableUntunneledUpgrade: true,
  275. disableEstablishing: false,
  276. disableApi: false,
  277. tunnelPoolSize: 1,
  278. useUpstreamProxy: false,
  279. disruptNetwork: false,
  280. useHostNameTransformer: false,
  281. runDuration: 0,
  282. })
  283. }
  284. func TestUnfrontedMeekHTTPS(t *testing.T) {
  285. controllerRun(t,
  286. &controllerRunConfig{
  287. expectNoServerEntries: false,
  288. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  289. clientIsLatestVersion: false,
  290. disableUntunneledUpgrade: true,
  291. disableEstablishing: false,
  292. disableApi: false,
  293. tunnelPoolSize: 1,
  294. useUpstreamProxy: false,
  295. disruptNetwork: false,
  296. useHostNameTransformer: false,
  297. runDuration: 0,
  298. })
  299. }
  300. func TestUnfrontedMeekHTTPSWithTransformer(t *testing.T) {
  301. controllerRun(t,
  302. &controllerRunConfig{
  303. expectNoServerEntries: false,
  304. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  305. clientIsLatestVersion: true,
  306. disableUntunneledUpgrade: true,
  307. disableEstablishing: false,
  308. disableApi: false,
  309. tunnelPoolSize: 1,
  310. useUpstreamProxy: false,
  311. disruptNetwork: false,
  312. useHostNameTransformer: true,
  313. runDuration: 0,
  314. })
  315. }
  316. func TestDisabledApi(t *testing.T) {
  317. controllerRun(t,
  318. &controllerRunConfig{
  319. expectNoServerEntries: false,
  320. protocol: "",
  321. clientIsLatestVersion: true,
  322. disableUntunneledUpgrade: true,
  323. disableEstablishing: false,
  324. disableApi: true,
  325. tunnelPoolSize: 1,
  326. useUpstreamProxy: false,
  327. disruptNetwork: false,
  328. useHostNameTransformer: false,
  329. runDuration: 0,
  330. })
  331. }
  332. func TestObfuscatedSSHWithUpstreamProxy(t *testing.T) {
  333. controllerRun(t,
  334. &controllerRunConfig{
  335. expectNoServerEntries: false,
  336. protocol: common.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  337. clientIsLatestVersion: false,
  338. disableUntunneledUpgrade: true,
  339. disableEstablishing: false,
  340. disableApi: false,
  341. tunnelPoolSize: 1,
  342. useUpstreamProxy: true,
  343. disruptNetwork: false,
  344. useHostNameTransformer: false,
  345. runDuration: 0,
  346. })
  347. }
  348. func TestUnfrontedMeekWithUpstreamProxy(t *testing.T) {
  349. controllerRun(t,
  350. &controllerRunConfig{
  351. expectNoServerEntries: false,
  352. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  353. clientIsLatestVersion: false,
  354. disableUntunneledUpgrade: true,
  355. disableEstablishing: false,
  356. disableApi: false,
  357. tunnelPoolSize: 1,
  358. useUpstreamProxy: true,
  359. disruptNetwork: false,
  360. useHostNameTransformer: false,
  361. runDuration: 0,
  362. })
  363. }
  364. func TestUnfrontedMeekHTTPSWithUpstreamProxy(t *testing.T) {
  365. controllerRun(t,
  366. &controllerRunConfig{
  367. expectNoServerEntries: false,
  368. protocol: common.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  369. clientIsLatestVersion: false,
  370. disableUntunneledUpgrade: true,
  371. disableEstablishing: false,
  372. disableApi: false,
  373. tunnelPoolSize: 1,
  374. useUpstreamProxy: true,
  375. disruptNetwork: false,
  376. useHostNameTransformer: false,
  377. runDuration: 0,
  378. })
  379. }
  380. type controllerRunConfig struct {
  381. expectNoServerEntries bool
  382. protocol string
  383. clientIsLatestVersion bool
  384. disableUntunneledUpgrade bool
  385. disableEstablishing bool
  386. disableApi bool
  387. tunnelPoolSize int
  388. useUpstreamProxy bool
  389. disruptNetwork bool
  390. useHostNameTransformer bool
  391. runDuration time.Duration
  392. }
  393. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  394. configFileContents, err := ioutil.ReadFile("controller_test.config")
  395. if err != nil {
  396. // Skip, don't fail, if config file is not present
  397. t.Skipf("error loading configuration file: %s", err)
  398. }
  399. config, err := LoadConfig(configFileContents)
  400. if err != nil {
  401. t.Fatalf("error processing configuration file: %s", err)
  402. }
  403. if runConfig.clientIsLatestVersion {
  404. config.ClientVersion = "999999999"
  405. }
  406. if runConfig.disableEstablishing {
  407. // Clear remote server list so tunnel cannot be established.
  408. // TODO: also delete all server entries in the datastore.
  409. config.RemoteServerListUrl = ""
  410. }
  411. if runConfig.disableApi {
  412. config.DisableApi = true
  413. }
  414. config.TunnelPoolSize = runConfig.tunnelPoolSize
  415. if runConfig.disableUntunneledUpgrade {
  416. // Disable untunneled upgrade downloader to ensure tunneled case is tested
  417. config.UpgradeDownloadClientVersionHeader = ""
  418. }
  419. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  420. t.Fatalf("cannot use multiple upstream proxies")
  421. }
  422. if runConfig.disruptNetwork {
  423. config.UpstreamProxyUrl = disruptorProxyURL
  424. } else if runConfig.useUpstreamProxy {
  425. config.UpstreamProxyUrl = upstreamProxyURL
  426. config.UpstreamProxyCustomHeaders = upstreamProxyCustomHeaders
  427. }
  428. if runConfig.useHostNameTransformer {
  429. config.HostNameTransformer = &TestHostNameTransformer{}
  430. }
  431. // Override client retry throttle values to speed up automated
  432. // tests and ensure tests complete within fixed deadlines.
  433. fetchRemoteServerListRetryPeriodSeconds := 0
  434. config.FetchRemoteServerListRetryPeriodSeconds = &fetchRemoteServerListRetryPeriodSeconds
  435. downloadUpgradeRetryPeriodSeconds := 0
  436. config.DownloadUpgradeRetryPeriodSeconds = &downloadUpgradeRetryPeriodSeconds
  437. establishTunnelPausePeriodSeconds := 1
  438. config.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  439. os.Remove(config.UpgradeDownloadFilename)
  440. config.TunnelProtocol = runConfig.protocol
  441. err = InitDataStore(config)
  442. if err != nil {
  443. t.Fatalf("error initializing datastore: %s", err)
  444. }
  445. serverEntryCount := CountServerEntries("", "")
  446. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  447. // TODO: replace expectNoServerEntries with resetServerEntries
  448. // so tests can run in arbitrary order
  449. t.Fatalf("unexpected server entries")
  450. }
  451. controller, err := NewController(config)
  452. if err != nil {
  453. t.Fatalf("error creating controller: %s", err)
  454. }
  455. // Monitor notices for "Tunnels" with count > 1, the
  456. // indication of tunnel establishment success.
  457. // Also record the selected HTTP proxy port to use
  458. // when fetching websites through the tunnel.
  459. httpProxyPort := 0
  460. tunnelEstablished := make(chan struct{}, 1)
  461. upgradeDownloaded := make(chan struct{}, 1)
  462. remoteServerListDownloaded := make(chan struct{}, 1)
  463. confirmedLatestVersion := make(chan struct{}, 1)
  464. var clientUpgradeDownloadedBytesCount int32
  465. var remoteServerListDownloadedBytesCount int32
  466. var impairedProtocolCount int32
  467. var impairedProtocolClassification = struct {
  468. sync.RWMutex
  469. classification map[string]int
  470. }{classification: make(map[string]int)}
  471. SetNoticeOutput(NewNoticeReceiver(
  472. func(notice []byte) {
  473. // TODO: log notices without logging server IPs:
  474. // fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  475. noticeType, payload, err := GetNotice(notice)
  476. if err != nil {
  477. return
  478. }
  479. switch noticeType {
  480. case "ListeningHttpProxyPort":
  481. httpProxyPort = int(payload["port"].(float64))
  482. case "ConnectingServer":
  483. serverProtocol := payload["protocol"].(string)
  484. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  485. // TODO: wrong goroutine for t.FatalNow()
  486. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  487. }
  488. case "Tunnels":
  489. count := int(payload["count"].(float64))
  490. if count > 0 {
  491. if runConfig.disableEstablishing {
  492. // TODO: wrong goroutine for t.FatalNow()
  493. t.Fatalf("tunnel established unexpectedly")
  494. } else {
  495. select {
  496. case tunnelEstablished <- *new(struct{}):
  497. default:
  498. }
  499. }
  500. }
  501. case "ClientUpgradeDownloadedBytes":
  502. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  503. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  504. case "ClientUpgradeDownloaded":
  505. select {
  506. case upgradeDownloaded <- *new(struct{}):
  507. default:
  508. }
  509. case "ClientIsLatestVersion":
  510. select {
  511. case confirmedLatestVersion <- *new(struct{}):
  512. default:
  513. }
  514. case "RemoteServerListDownloadedBytes":
  515. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  516. t.Logf("RemoteServerListDownloadedBytes: %d", int(payload["bytes"].(float64)))
  517. case "RemoteServerListDownloaded":
  518. select {
  519. case remoteServerListDownloaded <- *new(struct{}):
  520. default:
  521. }
  522. case "ImpairedProtocolClassification":
  523. classification := payload["classification"].(map[string]interface{})
  524. impairedProtocolClassification.Lock()
  525. impairedProtocolClassification.classification = make(map[string]int)
  526. for k, v := range classification {
  527. count := int(v.(float64))
  528. if count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  529. atomic.AddInt32(&impairedProtocolCount, 1)
  530. }
  531. impairedProtocolClassification.classification[k] = count
  532. }
  533. impairedProtocolClassification.Unlock()
  534. case "ActiveTunnel":
  535. serverProtocol := payload["protocol"].(string)
  536. classification := make(map[string]int)
  537. impairedProtocolClassification.RLock()
  538. for k, v := range impairedProtocolClassification.classification {
  539. classification[k] = v
  540. }
  541. impairedProtocolClassification.RUnlock()
  542. count, ok := classification[serverProtocol]
  543. if ok && count >= IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD {
  544. // TODO: wrong goroutine for t.FatalNow()
  545. t.Fatalf("unexpected tunnel using impaired protocol: %s, %+v",
  546. serverProtocol, classification)
  547. }
  548. }
  549. }))
  550. // Run controller, which establishes tunnels
  551. shutdownBroadcast := make(chan struct{})
  552. controllerWaitGroup := new(sync.WaitGroup)
  553. controllerWaitGroup.Add(1)
  554. go func() {
  555. defer controllerWaitGroup.Done()
  556. controller.Run(shutdownBroadcast)
  557. }()
  558. defer func() {
  559. // Test: shutdown must complete within 20 seconds
  560. close(shutdownBroadcast)
  561. shutdownTimeout := time.NewTimer(20 * time.Second)
  562. shutdownOk := make(chan struct{}, 1)
  563. go func() {
  564. controllerWaitGroup.Wait()
  565. shutdownOk <- *new(struct{})
  566. }()
  567. select {
  568. case <-shutdownOk:
  569. case <-shutdownTimeout.C:
  570. t.Fatalf("controller shutdown timeout exceeded")
  571. }
  572. }()
  573. if !runConfig.disableEstablishing {
  574. // Test: tunnel must be established within 120 seconds
  575. establishTimeout := time.NewTimer(120 * time.Second)
  576. select {
  577. case <-tunnelEstablished:
  578. case <-establishTimeout.C:
  579. t.Fatalf("tunnel establish timeout exceeded")
  580. }
  581. // Test: if starting with no server entries, a fetch remote
  582. // server list must have succeeded. With disruptNetwork, the
  583. // fetch must have been resumed at least once.
  584. if serverEntryCount == 0 {
  585. select {
  586. case <-remoteServerListDownloaded:
  587. default:
  588. t.Fatalf("expected remote server list downloaded")
  589. }
  590. if runConfig.disruptNetwork {
  591. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  592. if count <= 1 {
  593. t.Fatalf("unexpected remote server list download progress: %d", count)
  594. }
  595. }
  596. }
  597. // Test: fetch website through tunnel
  598. // Allow for known race condition described in NewHttpProxy():
  599. time.Sleep(1 * time.Second)
  600. fetchAndVerifyWebsite(t, httpProxyPort)
  601. // Test: run for duration, periodically using the tunnel to
  602. // ensure failed tunnel detection, and ultimately hitting
  603. // impaired protocol checks.
  604. startTime := monotime.Now()
  605. for {
  606. time.Sleep(1 * time.Second)
  607. useTunnel(t, httpProxyPort)
  608. if startTime.Add(runConfig.runDuration).Before(monotime.Now()) {
  609. break
  610. }
  611. }
  612. // Test: with disruptNetwork, impaired protocols should be exercised
  613. if runConfig.runDuration > 0 && runConfig.disruptNetwork {
  614. count := atomic.LoadInt32(&impairedProtocolCount)
  615. if count <= 0 {
  616. t.Fatalf("unexpected impaired protocol count: %d", count)
  617. } else {
  618. impairedProtocolClassification.RLock()
  619. t.Logf("impaired protocol classification: %+v",
  620. impairedProtocolClassification.classification)
  621. impairedProtocolClassification.RUnlock()
  622. }
  623. }
  624. }
  625. // Test: upgrade check/download must be downloaded within 180 seconds
  626. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  627. if expectUpgrade {
  628. upgradeTimeout := time.NewTimer(180 * time.Second)
  629. select {
  630. case <-upgradeDownloaded:
  631. // TODO: verify downloaded file
  632. if runConfig.clientIsLatestVersion {
  633. t.Fatalf("upgrade downloaded unexpectedly")
  634. }
  635. // Test: with disruptNetwork, must be multiple download progress notices
  636. if runConfig.disruptNetwork {
  637. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  638. if count <= 1 {
  639. t.Fatalf("unexpected upgrade download progress: %d", count)
  640. }
  641. }
  642. case <-confirmedLatestVersion:
  643. if !runConfig.clientIsLatestVersion {
  644. t.Fatalf("confirmed latest version unexpectedly")
  645. }
  646. case <-upgradeTimeout.C:
  647. t.Fatalf("upgrade download timeout exceeded")
  648. }
  649. }
  650. }
  651. type TestHostNameTransformer struct {
  652. }
  653. func (TestHostNameTransformer) TransformHostName(string) (string, bool) {
  654. return "example.com", true
  655. }
  656. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) {
  657. testUrl := "https://raw.githubusercontent.com/Psiphon-Labs/psiphon-tunnel-core/master/LICENSE"
  658. roundTripTimeout := 10 * time.Second
  659. expectedResponsePrefix := " GNU GENERAL PUBLIC LICENSE"
  660. expectedResponseSize := 35148
  661. checkResponse := func(responseBody string) bool {
  662. return strings.HasPrefix(responseBody, expectedResponsePrefix) && len(responseBody) == expectedResponseSize
  663. }
  664. // Test: use HTTP proxy
  665. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  666. if err != nil {
  667. t.Fatalf("error initializing proxied HTTP request: %s", err)
  668. }
  669. httpClient := &http.Client{
  670. Transport: &http.Transport{
  671. Proxy: http.ProxyURL(proxyUrl),
  672. },
  673. Timeout: roundTripTimeout,
  674. }
  675. response, err := httpClient.Get(testUrl)
  676. if err != nil {
  677. t.Fatalf("error sending proxied HTTP request: %s", err)
  678. }
  679. body, err := ioutil.ReadAll(response.Body)
  680. if err != nil {
  681. t.Fatalf("error reading proxied HTTP response: %s", err)
  682. }
  683. response.Body.Close()
  684. if !checkResponse(string(body)) {
  685. t.Fatalf("unexpected proxied HTTP response")
  686. }
  687. // Test: use direct URL proxy
  688. httpClient = &http.Client{
  689. Transport: http.DefaultTransport,
  690. Timeout: roundTripTimeout,
  691. }
  692. response, err = httpClient.Get(
  693. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  694. httpProxyPort, url.QueryEscape(testUrl)))
  695. if err != nil {
  696. t.Fatalf("error sending direct URL request: %s", err)
  697. }
  698. body, err = ioutil.ReadAll(response.Body)
  699. if err != nil {
  700. t.Fatalf("error reading direct URL response: %s", err)
  701. }
  702. response.Body.Close()
  703. if !checkResponse(string(body)) {
  704. t.Fatalf("unexpected direct URL response")
  705. }
  706. // Test: use tunneled URL proxy
  707. response, err = httpClient.Get(
  708. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  709. httpProxyPort, url.QueryEscape(testUrl)))
  710. if err != nil {
  711. t.Fatalf("error sending tunneled URL request: %s", err)
  712. }
  713. body, err = ioutil.ReadAll(response.Body)
  714. if err != nil {
  715. t.Fatalf("error reading tunneled URL response: %s", err)
  716. }
  717. response.Body.Close()
  718. if !checkResponse(string(body)) {
  719. t.Fatalf("unexpected tunneled URL response")
  720. }
  721. }
  722. func useTunnel(t *testing.T, httpProxyPort int) {
  723. // No action on errors as the tunnel is expected to fail sometimes
  724. testUrl := "https://psiphon3.com"
  725. roundTripTimeout := 1 * time.Second
  726. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  727. if err != nil {
  728. return
  729. }
  730. httpClient := &http.Client{
  731. Transport: &http.Transport{
  732. Proxy: http.ProxyURL(proxyUrl),
  733. },
  734. Timeout: roundTripTimeout,
  735. }
  736. response, err := httpClient.Get(testUrl)
  737. if err != nil {
  738. return
  739. }
  740. response.Body.Close()
  741. }
  742. const disruptorProxyAddress = "127.0.0.1:2160"
  743. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  744. const disruptorMaxConnectionBytes = 500000
  745. const disruptorMaxConnectionTime = 10 * time.Second
  746. func initDisruptor() {
  747. go func() {
  748. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  749. if err != nil {
  750. fmt.Errorf("disruptor proxy listen error: %s", err)
  751. return
  752. }
  753. for {
  754. localConn, err := listener.AcceptSocks()
  755. if err != nil {
  756. fmt.Errorf("disruptor proxy accept error: %s", err)
  757. return
  758. }
  759. go func() {
  760. defer localConn.Close()
  761. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  762. if err != nil {
  763. fmt.Errorf("disruptor proxy dial error: %s", err)
  764. return
  765. }
  766. defer remoteConn.Close()
  767. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  768. if err != nil {
  769. fmt.Errorf("disruptor proxy grant error: %s", err)
  770. return
  771. }
  772. // Cut connection after disruptorMaxConnectionTime
  773. time.AfterFunc(disruptorMaxConnectionTime, func() {
  774. localConn.Close()
  775. remoteConn.Close()
  776. })
  777. // Relay connection, but only up to disruptorMaxConnectionBytes
  778. waitGroup := new(sync.WaitGroup)
  779. waitGroup.Add(1)
  780. go func() {
  781. defer waitGroup.Done()
  782. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  783. }()
  784. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  785. waitGroup.Wait()
  786. }()
  787. }
  788. }()
  789. }
  790. const upstreamProxyURL = "http://127.0.0.1:2161"
  791. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": []string{"test-header-value1", "test-header-value2"}}
  792. func hasExpectedCustomHeaders(h http.Header) bool {
  793. for name, values := range upstreamProxyCustomHeaders {
  794. if h[name] == nil {
  795. return false
  796. }
  797. // Order may not be the same
  798. for _, value := range values {
  799. if !common.Contains(h[name], value) {
  800. return false
  801. }
  802. }
  803. }
  804. return true
  805. }
  806. func initUpstreamProxy() {
  807. go func() {
  808. proxy := goproxy.NewProxyHttpServer()
  809. proxy.OnRequest().DoFunc(
  810. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  811. if !hasExpectedCustomHeaders(r.Header) {
  812. ctx.Logf("missing expected headers: %+v", ctx.Req.Header)
  813. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  814. }
  815. return r, nil
  816. })
  817. proxy.OnRequest().HandleConnectFunc(
  818. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  819. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  820. ctx.Logf("missing expected headers: %+v", ctx.Req.Header)
  821. return goproxy.RejectConnect, host
  822. }
  823. return goproxy.OkConnect, host
  824. })
  825. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  826. if err != nil {
  827. fmt.Printf("upstream proxy failed: %s", err)
  828. }
  829. }()
  830. // TODO: wait until listener is active?
  831. }