controller_test.go 32 KB

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