controller_test.go 27 KB

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