controller_test.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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/protocol"
  42. "github.com/elazarl/goproxy"
  43. )
  44. var testDataDirName string
  45. func TestMain(m *testing.M) {
  46. flag.Parse()
  47. var err error
  48. testDataDirName, err = ioutil.TempDir("", "psiphon-controller-test")
  49. if err != nil {
  50. fmt.Printf("TempDir failed: %s\n", err)
  51. os.Exit(1)
  52. }
  53. defer os.RemoveAll(testDataDirName)
  54. os.Remove(filepath.Join(testDataDirName, DATA_STORE_FILENAME))
  55. SetEmitDiagnosticNotices(true)
  56. initDisruptor()
  57. initUpstreamProxy()
  58. os.Exit(m.Run())
  59. }
  60. // Test case notes/limitations/dependencies:
  61. //
  62. // * Untunneled upgrade tests must execute before
  63. // the other tests to ensure no tunnel is established.
  64. // We need a way to reset the datastore after it's been
  65. // initialized in order to to clear out its data entries
  66. // and be able to arbitrarily order the tests.
  67. //
  68. // * The resumable download tests using disruptNetwork
  69. // depend on the download object being larger than the
  70. // disruptorMax limits so that the disruptor will actually
  71. // interrupt the first download attempt. Specifically, the
  72. // upgrade and remote server list at the URLs specified in
  73. // controller_test.config.enc.
  74. //
  75. // * The protocol tests assume there is at least one server
  76. // supporting each protocol in the server list at the URL
  77. // specified in controller_test.config.enc, and that these
  78. // servers are not overloaded.
  79. //
  80. // * fetchAndVerifyWebsite depends on the target URL being
  81. // available and responding.
  82. //
  83. func TestUntunneledUpgradeDownload(t *testing.T) {
  84. controllerRun(t,
  85. &controllerRunConfig{
  86. expectNoServerEntries: true,
  87. protocol: "",
  88. clientIsLatestVersion: false,
  89. disableUntunneledUpgrade: false,
  90. disableEstablishing: true,
  91. disableApi: false,
  92. tunnelPoolSize: 1,
  93. useUpstreamProxy: false,
  94. disruptNetwork: false,
  95. transformHostNames: false,
  96. runDuration: 0,
  97. })
  98. }
  99. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  100. controllerRun(t,
  101. &controllerRunConfig{
  102. expectNoServerEntries: true,
  103. protocol: "",
  104. clientIsLatestVersion: false,
  105. disableUntunneledUpgrade: false,
  106. disableEstablishing: true,
  107. disableApi: false,
  108. tunnelPoolSize: 1,
  109. useUpstreamProxy: false,
  110. disruptNetwork: true,
  111. transformHostNames: false,
  112. runDuration: 0,
  113. })
  114. }
  115. func TestUntunneledUpgradeClientIsLatestVersion(t *testing.T) {
  116. controllerRun(t,
  117. &controllerRunConfig{
  118. expectNoServerEntries: true,
  119. protocol: "",
  120. clientIsLatestVersion: true,
  121. disableUntunneledUpgrade: false,
  122. disableEstablishing: true,
  123. disableApi: false,
  124. tunnelPoolSize: 1,
  125. useUpstreamProxy: false,
  126. disruptNetwork: false,
  127. transformHostNames: false,
  128. runDuration: 0,
  129. })
  130. }
  131. func TestUntunneledResumableFetchRemoteServerList(t *testing.T) {
  132. controllerRun(t,
  133. &controllerRunConfig{
  134. expectNoServerEntries: true,
  135. protocol: "",
  136. clientIsLatestVersion: true,
  137. disableUntunneledUpgrade: false,
  138. disableEstablishing: false,
  139. disableApi: false,
  140. tunnelPoolSize: 1,
  141. useUpstreamProxy: false,
  142. disruptNetwork: true,
  143. transformHostNames: false,
  144. runDuration: 0,
  145. })
  146. }
  147. func TestTunneledUpgradeClientIsLatestVersion(t *testing.T) {
  148. controllerRun(t,
  149. &controllerRunConfig{
  150. expectNoServerEntries: false,
  151. protocol: "",
  152. clientIsLatestVersion: true,
  153. disableUntunneledUpgrade: true,
  154. disableEstablishing: false,
  155. disableApi: false,
  156. tunnelPoolSize: 1,
  157. useUpstreamProxy: false,
  158. disruptNetwork: false,
  159. transformHostNames: false,
  160. runDuration: 0,
  161. })
  162. }
  163. func TestImpairedProtocols(t *testing.T) {
  164. // This test sets a tunnelPoolSize of 40 and runs
  165. // the session for 1 minute with network disruption
  166. // on. All 40 tunnels being disrupted every 10
  167. // seconds (followed by ssh keep alive probe timeout)
  168. // should be sufficient to trigger at least one
  169. // impaired protocol classification.
  170. controllerRun(t,
  171. &controllerRunConfig{
  172. expectNoServerEntries: false,
  173. protocol: "",
  174. clientIsLatestVersion: true,
  175. disableUntunneledUpgrade: true,
  176. disableEstablishing: false,
  177. disableApi: false,
  178. tunnelPoolSize: 40,
  179. useUpstreamProxy: false,
  180. disruptNetwork: true,
  181. transformHostNames: false,
  182. runDuration: 1 * time.Minute,
  183. })
  184. }
  185. func TestSSH(t *testing.T) {
  186. controllerRun(t,
  187. &controllerRunConfig{
  188. expectNoServerEntries: false,
  189. protocol: protocol.TUNNEL_PROTOCOL_SSH,
  190. clientIsLatestVersion: false,
  191. disableUntunneledUpgrade: true,
  192. disableEstablishing: false,
  193. disableApi: false,
  194. tunnelPoolSize: 1,
  195. useUpstreamProxy: false,
  196. disruptNetwork: false,
  197. transformHostNames: false,
  198. runDuration: 0,
  199. })
  200. }
  201. func TestObfuscatedSSH(t *testing.T) {
  202. controllerRun(t,
  203. &controllerRunConfig{
  204. expectNoServerEntries: false,
  205. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  206. clientIsLatestVersion: false,
  207. disableUntunneledUpgrade: true,
  208. disableEstablishing: false,
  209. disableApi: false,
  210. tunnelPoolSize: 1,
  211. useUpstreamProxy: false,
  212. disruptNetwork: false,
  213. transformHostNames: false,
  214. runDuration: 0,
  215. })
  216. }
  217. func TestUnfrontedMeek(t *testing.T) {
  218. controllerRun(t,
  219. &controllerRunConfig{
  220. expectNoServerEntries: false,
  221. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  222. clientIsLatestVersion: false,
  223. disableUntunneledUpgrade: true,
  224. disableEstablishing: false,
  225. disableApi: false,
  226. tunnelPoolSize: 1,
  227. useUpstreamProxy: false,
  228. disruptNetwork: false,
  229. transformHostNames: false,
  230. runDuration: 0,
  231. })
  232. }
  233. func TestUnfrontedMeekWithTransformer(t *testing.T) {
  234. controllerRun(t,
  235. &controllerRunConfig{
  236. expectNoServerEntries: false,
  237. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  238. clientIsLatestVersion: true,
  239. disableUntunneledUpgrade: true,
  240. disableEstablishing: false,
  241. disableApi: false,
  242. tunnelPoolSize: 1,
  243. useUpstreamProxy: false,
  244. disruptNetwork: false,
  245. transformHostNames: true,
  246. runDuration: 0,
  247. })
  248. }
  249. func TestFrontedMeek(t *testing.T) {
  250. controllerRun(t,
  251. &controllerRunConfig{
  252. expectNoServerEntries: false,
  253. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  254. clientIsLatestVersion: false,
  255. disableUntunneledUpgrade: true,
  256. disableEstablishing: false,
  257. disableApi: false,
  258. tunnelPoolSize: 1,
  259. useUpstreamProxy: false,
  260. disruptNetwork: false,
  261. transformHostNames: false,
  262. runDuration: 0,
  263. })
  264. }
  265. func TestFrontedMeekWithTransformer(t *testing.T) {
  266. controllerRun(t,
  267. &controllerRunConfig{
  268. expectNoServerEntries: false,
  269. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK,
  270. clientIsLatestVersion: true,
  271. disableUntunneledUpgrade: true,
  272. disableEstablishing: false,
  273. disableApi: false,
  274. tunnelPoolSize: 1,
  275. useUpstreamProxy: false,
  276. disruptNetwork: false,
  277. transformHostNames: true,
  278. runDuration: 0,
  279. })
  280. }
  281. func TestFrontedMeekHTTP(t *testing.T) {
  282. controllerRun(t,
  283. &controllerRunConfig{
  284. expectNoServerEntries: false,
  285. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP,
  286. clientIsLatestVersion: true,
  287. disableUntunneledUpgrade: true,
  288. disableEstablishing: false,
  289. disableApi: false,
  290. tunnelPoolSize: 1,
  291. useUpstreamProxy: false,
  292. disruptNetwork: false,
  293. transformHostNames: false,
  294. runDuration: 0,
  295. })
  296. }
  297. func TestUnfrontedMeekHTTPS(t *testing.T) {
  298. controllerRun(t,
  299. &controllerRunConfig{
  300. expectNoServerEntries: false,
  301. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  302. clientIsLatestVersion: false,
  303. disableUntunneledUpgrade: true,
  304. disableEstablishing: false,
  305. disableApi: false,
  306. tunnelPoolSize: 1,
  307. useUpstreamProxy: false,
  308. disruptNetwork: false,
  309. transformHostNames: false,
  310. runDuration: 0,
  311. })
  312. }
  313. func TestUnfrontedMeekHTTPSWithTransformer(t *testing.T) {
  314. controllerRun(t,
  315. &controllerRunConfig{
  316. expectNoServerEntries: false,
  317. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  318. clientIsLatestVersion: true,
  319. disableUntunneledUpgrade: true,
  320. disableEstablishing: false,
  321. disableApi: false,
  322. tunnelPoolSize: 1,
  323. useUpstreamProxy: false,
  324. disruptNetwork: false,
  325. transformHostNames: true,
  326. runDuration: 0,
  327. })
  328. }
  329. func TestDisabledApi(t *testing.T) {
  330. controllerRun(t,
  331. &controllerRunConfig{
  332. expectNoServerEntries: false,
  333. protocol: "",
  334. clientIsLatestVersion: true,
  335. disableUntunneledUpgrade: true,
  336. disableEstablishing: false,
  337. disableApi: true,
  338. tunnelPoolSize: 1,
  339. useUpstreamProxy: false,
  340. disruptNetwork: false,
  341. transformHostNames: false,
  342. runDuration: 0,
  343. })
  344. }
  345. func TestObfuscatedSSHWithUpstreamProxy(t *testing.T) {
  346. controllerRun(t,
  347. &controllerRunConfig{
  348. expectNoServerEntries: false,
  349. protocol: protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH,
  350. clientIsLatestVersion: false,
  351. disableUntunneledUpgrade: true,
  352. disableEstablishing: false,
  353. disableApi: false,
  354. tunnelPoolSize: 1,
  355. useUpstreamProxy: true,
  356. disruptNetwork: false,
  357. transformHostNames: false,
  358. runDuration: 0,
  359. })
  360. }
  361. func TestUnfrontedMeekWithUpstreamProxy(t *testing.T) {
  362. controllerRun(t,
  363. &controllerRunConfig{
  364. expectNoServerEntries: false,
  365. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK,
  366. clientIsLatestVersion: false,
  367. disableUntunneledUpgrade: true,
  368. disableEstablishing: false,
  369. disableApi: false,
  370. tunnelPoolSize: 1,
  371. useUpstreamProxy: true,
  372. disruptNetwork: false,
  373. transformHostNames: false,
  374. runDuration: 0,
  375. })
  376. }
  377. func TestUnfrontedMeekHTTPSWithUpstreamProxy(t *testing.T) {
  378. controllerRun(t,
  379. &controllerRunConfig{
  380. expectNoServerEntries: false,
  381. protocol: protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  382. clientIsLatestVersion: false,
  383. disableUntunneledUpgrade: true,
  384. disableEstablishing: false,
  385. disableApi: false,
  386. tunnelPoolSize: 1,
  387. useUpstreamProxy: true,
  388. disruptNetwork: false,
  389. transformHostNames: false,
  390. runDuration: 0,
  391. })
  392. }
  393. type controllerRunConfig struct {
  394. expectNoServerEntries bool
  395. protocol string
  396. clientIsLatestVersion bool
  397. disableUntunneledUpgrade bool
  398. disableEstablishing bool
  399. disableApi bool
  400. tunnelPoolSize int
  401. useUpstreamProxy bool
  402. disruptNetwork bool
  403. transformHostNames bool
  404. runDuration time.Duration
  405. }
  406. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  407. configJSON, err := ioutil.ReadFile("controller_test.config")
  408. if err != nil {
  409. // Skip, don't fail, if config file is not present
  410. t.Skipf("error loading configuration file: %s", err)
  411. }
  412. // These fields must be filled in before calling LoadConfig
  413. var modifyConfig map[string]interface{}
  414. json.Unmarshal(configJSON, &modifyConfig)
  415. modifyConfig["DataStoreDirectory"] = testDataDirName
  416. modifyConfig["RemoteServerListDownloadFilename"] = filepath.Join(testDataDirName, "server_list_compressed")
  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.CustomHeaders = 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 := 1
  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. SetNoticeWriter(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. ctx, cancelFunc := context.WithCancel(context.Background())
  587. controllerWaitGroup := new(sync.WaitGroup)
  588. controllerWaitGroup.Add(1)
  589. go func() {
  590. defer controllerWaitGroup.Done()
  591. controller.Run(ctx)
  592. }()
  593. defer func() {
  594. // Test: shutdown must complete within 20 seconds
  595. cancelFunc()
  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. if !runConfig.disruptNetwork {
  638. fetchAndVerifyWebsite(t, httpProxyPort)
  639. }
  640. // Test: run for duration, periodically using the tunnel to
  641. // ensure failed tunnel detection, and ultimately hitting
  642. // impaired protocol checks.
  643. startTime := monotime.Now()
  644. for {
  645. time.Sleep(1 * time.Second)
  646. useTunnel(t, httpProxyPort)
  647. if startTime.Add(runConfig.runDuration).Before(monotime.Now()) {
  648. break
  649. }
  650. }
  651. // Test: with disruptNetwork, impaired protocols should be exercised
  652. if runConfig.runDuration > 0 && runConfig.disruptNetwork {
  653. count := atomic.LoadInt32(&impairedProtocolCount)
  654. if count <= 0 {
  655. t.Fatalf("unexpected impaired protocol count: %d", count)
  656. } else {
  657. impairedProtocolClassification.RLock()
  658. t.Logf("impaired protocol classification: %+v",
  659. impairedProtocolClassification.classification)
  660. impairedProtocolClassification.RUnlock()
  661. }
  662. }
  663. }
  664. }
  665. // Test: upgrade check/download must be downloaded within 180 seconds
  666. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  667. if expectUpgrade {
  668. upgradeTimeout := time.NewTimer(120 * time.Second)
  669. select {
  670. case <-upgradeDownloaded:
  671. // TODO: verify downloaded file
  672. if runConfig.clientIsLatestVersion {
  673. t.Fatalf("upgrade downloaded unexpectedly")
  674. }
  675. // Test: with disruptNetwork, must be multiple download progress notices
  676. if runConfig.disruptNetwork {
  677. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  678. if count <= 1 {
  679. t.Fatalf("unexpected upgrade download progress: %d", count)
  680. }
  681. }
  682. case <-confirmedLatestVersion:
  683. if !runConfig.clientIsLatestVersion {
  684. t.Fatalf("confirmed latest version unexpectedly")
  685. }
  686. case <-upgradeTimeout.C:
  687. t.Fatalf("upgrade download timeout exceeded")
  688. }
  689. }
  690. }
  691. type TestHostNameTransformer struct {
  692. }
  693. func (TestHostNameTransformer) TransformHostName(string) (string, bool) {
  694. return "example.com", true
  695. }
  696. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  697. testUrl := "https://psiphon.ca"
  698. roundTripTimeout := 30 * time.Second
  699. expectedResponseContains := "Psiphon"
  700. checkResponse := func(responseBody string) bool {
  701. return strings.Contains(responseBody, expectedResponseContains)
  702. }
  703. // Retries are made to compensate for intermittent failures due
  704. // to external network conditions.
  705. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  706. retryCount := 6
  707. retryDelay := 5 * time.Second
  708. var err error
  709. for i := 0; i < retryCount; i++ {
  710. err = fetchFunc()
  711. if err == nil || i == retryCount-1 {
  712. break
  713. }
  714. time.Sleep(retryDelay)
  715. t.Logf("retrying %s...", fetchName)
  716. }
  717. return err
  718. }
  719. // Test: use HTTP proxy
  720. fetchUsingHTTPProxy := func() error {
  721. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  722. if err != nil {
  723. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  724. }
  725. httpTransport := &http.Transport{
  726. Proxy: http.ProxyURL(proxyUrl),
  727. DisableKeepAlives: true,
  728. }
  729. httpClient := &http.Client{
  730. Transport: httpTransport,
  731. Timeout: roundTripTimeout,
  732. }
  733. request, err := http.NewRequest("GET", testUrl, nil)
  734. if err != nil {
  735. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  736. }
  737. response, err := httpClient.Do(request)
  738. if err != nil {
  739. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  740. }
  741. defer response.Body.Close()
  742. body, err := ioutil.ReadAll(response.Body)
  743. if err != nil {
  744. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  745. }
  746. if !checkResponse(string(body)) {
  747. return fmt.Errorf("unexpected proxied HTTP response")
  748. }
  749. return nil
  750. }
  751. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  752. if err != nil {
  753. return err
  754. }
  755. // Delay before requesting from external service again
  756. time.Sleep(1 * time.Second)
  757. // Test: use direct URL proxy
  758. fetchUsingURLProxyDirect := func() error {
  759. httpTransport := &http.Transport{
  760. DisableKeepAlives: true,
  761. }
  762. httpClient := &http.Client{
  763. Transport: httpTransport,
  764. Timeout: roundTripTimeout,
  765. }
  766. request, err := http.NewRequest(
  767. "GET",
  768. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  769. httpProxyPort, url.QueryEscape(testUrl)),
  770. nil)
  771. if err != nil {
  772. return fmt.Errorf("error preparing direct URL request: %s", err)
  773. }
  774. response, err := httpClient.Do(request)
  775. if err != nil {
  776. return fmt.Errorf("error sending direct URL request: %s", err)
  777. }
  778. defer response.Body.Close()
  779. body, err := ioutil.ReadAll(response.Body)
  780. if err != nil {
  781. return fmt.Errorf("error reading direct URL response: %s", err)
  782. }
  783. if !checkResponse(string(body)) {
  784. return fmt.Errorf("unexpected direct URL response")
  785. }
  786. return nil
  787. }
  788. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  789. if err != nil {
  790. return err
  791. }
  792. // Delay before requesting from external service again
  793. time.Sleep(1 * time.Second)
  794. // Test: use tunneled URL proxy
  795. fetchUsingURLProxyTunneled := func() error {
  796. httpTransport := &http.Transport{
  797. DisableKeepAlives: true,
  798. }
  799. httpClient := &http.Client{
  800. Transport: httpTransport,
  801. Timeout: roundTripTimeout,
  802. }
  803. request, err := http.NewRequest(
  804. "GET",
  805. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  806. httpProxyPort, url.QueryEscape(testUrl)),
  807. nil)
  808. if err != nil {
  809. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  810. }
  811. response, err := httpClient.Do(request)
  812. if err != nil {
  813. return fmt.Errorf("error sending tunneled URL request: %s", err)
  814. }
  815. defer response.Body.Close()
  816. body, err := ioutil.ReadAll(response.Body)
  817. if err != nil {
  818. return fmt.Errorf("error reading tunneled URL response: %s", err)
  819. }
  820. if !checkResponse(string(body)) {
  821. return fmt.Errorf("unexpected tunneled URL response")
  822. }
  823. return nil
  824. }
  825. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  826. if err != nil {
  827. return err
  828. }
  829. return nil
  830. }
  831. func useTunnel(t *testing.T, httpProxyPort int) {
  832. // No action on errors as the tunnel is expected to fail sometimes
  833. testUrl := "https://psiphon3.com"
  834. roundTripTimeout := 1 * time.Second
  835. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  836. if err != nil {
  837. return
  838. }
  839. httpClient := &http.Client{
  840. Transport: &http.Transport{
  841. Proxy: http.ProxyURL(proxyUrl),
  842. },
  843. Timeout: roundTripTimeout,
  844. }
  845. response, err := httpClient.Get(testUrl)
  846. if err != nil {
  847. return
  848. }
  849. response.Body.Close()
  850. }
  851. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  852. // network; for example, the size of the remote server list resource must exceed
  853. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  854. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  855. // too small, the test will take longer to run since more retries are necessary.
  856. //
  857. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  858. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  859. // these test in controller_test serve the dual purpose of ensuring that tunnel
  860. // core works with the production network.
  861. //
  862. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  863. // based on current production network configuration?
  864. const disruptorProxyAddress = "127.0.0.1:2160"
  865. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  866. const disruptorMaxConnectionBytes = 250000
  867. const disruptorMaxConnectionTime = 10 * time.Second
  868. func initDisruptor() {
  869. go func() {
  870. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  871. if err != nil {
  872. fmt.Printf("disruptor proxy listen error: %s\n", err)
  873. return
  874. }
  875. for {
  876. localConn, err := listener.AcceptSocks()
  877. if err != nil {
  878. if e, ok := err.(net.Error); ok && e.Temporary() {
  879. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  880. continue
  881. }
  882. fmt.Printf("disruptor proxy accept error: %s\n", err)
  883. return
  884. }
  885. go func() {
  886. defer localConn.Close()
  887. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  888. if err != nil {
  889. // TODO: log "err" without logging server IPs
  890. fmt.Printf("disruptor proxy dial error\n")
  891. return
  892. }
  893. defer remoteConn.Close()
  894. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  895. if err != nil {
  896. fmt.Printf("disruptor proxy grant error: %s\n", err)
  897. return
  898. }
  899. // Cut connection after disruptorMaxConnectionTime
  900. time.AfterFunc(disruptorMaxConnectionTime, func() {
  901. localConn.Close()
  902. remoteConn.Close()
  903. })
  904. // Relay connection, but only up to disruptorMaxConnectionBytes
  905. waitGroup := new(sync.WaitGroup)
  906. waitGroup.Add(1)
  907. go func() {
  908. defer waitGroup.Done()
  909. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  910. localConn.Close()
  911. remoteConn.Close()
  912. }()
  913. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  914. localConn.Close()
  915. remoteConn.Close()
  916. waitGroup.Wait()
  917. }()
  918. }
  919. }()
  920. }
  921. const upstreamProxyURL = "http://127.0.0.1:2161"
  922. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  923. func hasExpectedCustomHeaders(h http.Header) bool {
  924. for name, values := range upstreamProxyCustomHeaders {
  925. if h[name] == nil {
  926. return false
  927. }
  928. // Order may not be the same
  929. for _, value := range values {
  930. if !common.Contains(h[name], value) {
  931. return false
  932. }
  933. }
  934. }
  935. return true
  936. }
  937. func initUpstreamProxy() {
  938. go func() {
  939. proxy := goproxy.NewProxyHttpServer()
  940. proxy.Logger = log.New(ioutil.Discard, "", 0)
  941. proxy.OnRequest().DoFunc(
  942. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  943. if !hasExpectedCustomHeaders(r.Header) {
  944. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  945. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  946. }
  947. return r, nil
  948. })
  949. proxy.OnRequest().HandleConnectFunc(
  950. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  951. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  952. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  953. return goproxy.RejectConnect, host
  954. }
  955. return goproxy.OkConnect, host
  956. })
  957. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  958. if err != nil {
  959. fmt.Printf("upstream proxy failed: %s\n", err)
  960. }
  961. }()
  962. // TODO: wait until listener is active?
  963. }