controller_test.go 27 KB

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