controller_test.go 28 KB

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