controller_test.go 29 KB

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