controller_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. // All config fields should be set before calling Commit.
  465. err = config.Commit()
  466. if err != nil {
  467. t.Fatalf("error committing configuration file: %s", err)
  468. }
  469. // Enable tactics requests. This will passively exercise the code
  470. // paths. server_test runs a more comprehensive test that checks
  471. // that the tactics request succeeds.
  472. config.NetworkID = "NETWORK1"
  473. os.Remove(config.UpgradeDownloadFilename)
  474. os.Remove(config.RemoteServerListDownloadFilename)
  475. err = InitDataStore(config)
  476. if err != nil {
  477. t.Fatalf("error initializing datastore: %s", err)
  478. }
  479. serverEntryCount := CountServerEntries("", nil)
  480. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  481. // TODO: replace expectNoServerEntries with resetServerEntries
  482. // so tests can run in arbitrary order
  483. t.Fatalf("unexpected server entries")
  484. }
  485. controller, err := NewController(config)
  486. if err != nil {
  487. t.Fatalf("error creating controller: %s", err)
  488. }
  489. // Monitor notices for "Tunnels" with count > 1, the
  490. // indication of tunnel establishment success.
  491. // Also record the selected HTTP proxy port to use
  492. // when fetching websites through the tunnel.
  493. httpProxyPort := 0
  494. tunnelEstablished := make(chan struct{}, 1)
  495. upgradeDownloaded := make(chan struct{}, 1)
  496. remoteServerListDownloaded := make(chan struct{}, 1)
  497. confirmedLatestVersion := make(chan struct{}, 1)
  498. var clientUpgradeDownloadedBytesCount int32
  499. var remoteServerListDownloadedBytesCount int32
  500. var impairedProtocolCount int32
  501. var impairedProtocolClassification = struct {
  502. sync.RWMutex
  503. classification map[string]int
  504. }{classification: make(map[string]int)}
  505. SetNoticeWriter(NewNoticeReceiver(
  506. func(notice []byte) {
  507. // TODO: log notices without logging server IPs:
  508. // fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  509. noticeType, payload, err := GetNotice(notice)
  510. if err != nil {
  511. return
  512. }
  513. switch noticeType {
  514. case "ListeningHttpProxyPort":
  515. httpProxyPort = int(payload["port"].(float64))
  516. case "ConnectingServer":
  517. serverProtocol := payload["protocol"].(string)
  518. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  519. // TODO: wrong goroutine for t.FatalNow()
  520. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  521. }
  522. case "Tunnels":
  523. count := int(payload["count"].(float64))
  524. if count > 0 {
  525. if runConfig.disableEstablishing {
  526. // TODO: wrong goroutine for t.FatalNow()
  527. t.Fatalf("tunnel established unexpectedly")
  528. } else {
  529. select {
  530. case tunnelEstablished <- *new(struct{}):
  531. default:
  532. }
  533. }
  534. }
  535. case "ClientUpgradeDownloadedBytes":
  536. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  537. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  538. case "ClientUpgradeDownloaded":
  539. select {
  540. case upgradeDownloaded <- *new(struct{}):
  541. default:
  542. }
  543. case "ClientIsLatestVersion":
  544. select {
  545. case confirmedLatestVersion <- *new(struct{}):
  546. default:
  547. }
  548. case "RemoteServerListResourceDownloadedBytes":
  549. url := payload["url"].(string)
  550. if url == config.RemoteServerListUrl {
  551. t.Logf("RemoteServerListResourceDownloadedBytes: %d", int(payload["bytes"].(float64)))
  552. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  553. }
  554. case "RemoteServerListResourceDownloaded":
  555. url := payload["url"].(string)
  556. if url == config.RemoteServerListUrl {
  557. t.Logf("RemoteServerListResourceDownloaded")
  558. select {
  559. case remoteServerListDownloaded <- *new(struct{}):
  560. default:
  561. }
  562. }
  563. case "ImpairedProtocolClassification":
  564. classification := payload["classification"].(map[string]interface{})
  565. impairedProtocolClassification.Lock()
  566. impairedProtocolClassification.classification = make(map[string]int)
  567. for k, v := range classification {
  568. count := int(v.(float64))
  569. if count >= config.clientParameters.Get().Int(parameters.ImpairedProtocolClassificationThreshold) {
  570. atomic.AddInt32(&impairedProtocolCount, 1)
  571. }
  572. impairedProtocolClassification.classification[k] = count
  573. }
  574. impairedProtocolClassification.Unlock()
  575. case "ActiveTunnel":
  576. serverProtocol := payload["protocol"].(string)
  577. classification := make(map[string]int)
  578. impairedProtocolClassification.RLock()
  579. for k, v := range impairedProtocolClassification.classification {
  580. classification[k] = v
  581. }
  582. impairedProtocolClassification.RUnlock()
  583. count, ok := classification[serverProtocol]
  584. if ok && count >= config.clientParameters.Get().Int(parameters.ImpairedProtocolClassificationThreshold) {
  585. // TODO: Fix this test case. Use of TunnelPoolSize breaks this
  586. // case, as many tunnel establishments are occurring in parallel,
  587. // and it can happen that a protocol is classified as impaired
  588. // while a tunnel with that protocol is established and set
  589. // active.
  590. // *not* t.Fatalf
  591. t.Logf("unexpected tunnel using impaired protocol: %s, %+v",
  592. serverProtocol, classification)
  593. }
  594. }
  595. }))
  596. // Run controller, which establishes tunnels
  597. ctx, cancelFunc := context.WithCancel(context.Background())
  598. controllerWaitGroup := new(sync.WaitGroup)
  599. controllerWaitGroup.Add(1)
  600. go func() {
  601. defer controllerWaitGroup.Done()
  602. controller.Run(ctx)
  603. }()
  604. defer func() {
  605. // Test: shutdown must complete within 20 seconds
  606. cancelFunc()
  607. shutdownTimeout := time.NewTimer(20 * time.Second)
  608. shutdownOk := make(chan struct{}, 1)
  609. go func() {
  610. controllerWaitGroup.Wait()
  611. shutdownOk <- *new(struct{})
  612. }()
  613. select {
  614. case <-shutdownOk:
  615. case <-shutdownTimeout.C:
  616. t.Fatalf("controller shutdown timeout exceeded")
  617. }
  618. }()
  619. if !runConfig.disableEstablishing {
  620. // Test: tunnel must be established within 120 seconds
  621. establishTimeout := time.NewTimer(120 * time.Second)
  622. select {
  623. case <-tunnelEstablished:
  624. case <-establishTimeout.C:
  625. t.Fatalf("tunnel establish timeout exceeded")
  626. }
  627. // Test: if starting with no server entries, a fetch remote
  628. // server list must have succeeded. With disruptNetwork, the
  629. // fetch must have been resumed at least once.
  630. if serverEntryCount == 0 {
  631. select {
  632. case <-remoteServerListDownloaded:
  633. default:
  634. t.Fatalf("expected remote server list downloaded")
  635. }
  636. if runConfig.disruptNetwork {
  637. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  638. if count <= 1 {
  639. t.Fatalf("unexpected remote server list download progress: %d", count)
  640. }
  641. }
  642. }
  643. // Cannot establish port forwards in DisableApi mode
  644. if !runConfig.disableApi {
  645. // Test: fetch website through tunnel
  646. // Allow for known race condition described in NewHttpProxy():
  647. time.Sleep(1 * time.Second)
  648. if !runConfig.disruptNetwork {
  649. fetchAndVerifyWebsite(t, httpProxyPort)
  650. }
  651. // Test: run for duration, periodically using the tunnel to
  652. // ensure failed tunnel detection, and ultimately hitting
  653. // impaired protocol checks.
  654. startTime := monotime.Now()
  655. for {
  656. time.Sleep(1 * time.Second)
  657. useTunnel(t, httpProxyPort)
  658. if startTime.Add(runConfig.runDuration).Before(monotime.Now()) {
  659. break
  660. }
  661. }
  662. // Test: with disruptNetwork, impaired protocols should be exercised
  663. if runConfig.runDuration > 0 && runConfig.disruptNetwork {
  664. count := atomic.LoadInt32(&impairedProtocolCount)
  665. if count <= 0 {
  666. t.Fatalf("unexpected impaired protocol count: %d", count)
  667. } else {
  668. impairedProtocolClassification.RLock()
  669. t.Logf("impaired protocol classification: %+v",
  670. impairedProtocolClassification.classification)
  671. impairedProtocolClassification.RUnlock()
  672. }
  673. }
  674. }
  675. }
  676. // Test: upgrade check/download must be downloaded within 180 seconds
  677. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  678. if expectUpgrade {
  679. upgradeTimeout := time.NewTimer(120 * time.Second)
  680. select {
  681. case <-upgradeDownloaded:
  682. // TODO: verify downloaded file
  683. if runConfig.clientIsLatestVersion {
  684. t.Fatalf("upgrade downloaded unexpectedly")
  685. }
  686. // Test: with disruptNetwork, must be multiple download progress notices
  687. if runConfig.disruptNetwork {
  688. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  689. if count <= 1 {
  690. t.Fatalf("unexpected upgrade download progress: %d", count)
  691. }
  692. }
  693. case <-confirmedLatestVersion:
  694. if !runConfig.clientIsLatestVersion {
  695. t.Fatalf("confirmed latest version unexpectedly")
  696. }
  697. case <-upgradeTimeout.C:
  698. t.Fatalf("upgrade download timeout exceeded")
  699. }
  700. }
  701. }
  702. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  703. testUrl := "https://psiphon.ca"
  704. roundTripTimeout := 30 * time.Second
  705. expectedResponseContains := "Psiphon"
  706. checkResponse := func(responseBody string) bool {
  707. return strings.Contains(responseBody, expectedResponseContains)
  708. }
  709. // Retries are made to compensate for intermittent failures due
  710. // to external network conditions.
  711. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  712. retryCount := 6
  713. retryDelay := 5 * time.Second
  714. var err error
  715. for i := 0; i < retryCount; i++ {
  716. err = fetchFunc()
  717. if err == nil || i == retryCount-1 {
  718. break
  719. }
  720. time.Sleep(retryDelay)
  721. t.Logf("retrying %s...", fetchName)
  722. }
  723. return err
  724. }
  725. // Test: use HTTP proxy
  726. fetchUsingHTTPProxy := func() error {
  727. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  728. if err != nil {
  729. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  730. }
  731. httpTransport := &http.Transport{
  732. Proxy: http.ProxyURL(proxyUrl),
  733. DisableKeepAlives: true,
  734. }
  735. httpClient := &http.Client{
  736. Transport: httpTransport,
  737. Timeout: roundTripTimeout,
  738. }
  739. request, err := http.NewRequest("GET", testUrl, nil)
  740. if err != nil {
  741. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  742. }
  743. response, err := httpClient.Do(request)
  744. if err != nil {
  745. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  746. }
  747. defer response.Body.Close()
  748. body, err := ioutil.ReadAll(response.Body)
  749. if err != nil {
  750. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  751. }
  752. if !checkResponse(string(body)) {
  753. return fmt.Errorf("unexpected proxied HTTP response")
  754. }
  755. return nil
  756. }
  757. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  758. if err != nil {
  759. return err
  760. }
  761. // Delay before requesting from external service again
  762. time.Sleep(1 * time.Second)
  763. // Test: use direct URL proxy
  764. fetchUsingURLProxyDirect := func() error {
  765. httpTransport := &http.Transport{
  766. DisableKeepAlives: true,
  767. }
  768. httpClient := &http.Client{
  769. Transport: httpTransport,
  770. Timeout: roundTripTimeout,
  771. }
  772. request, err := http.NewRequest(
  773. "GET",
  774. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  775. httpProxyPort, url.QueryEscape(testUrl)),
  776. nil)
  777. if err != nil {
  778. return fmt.Errorf("error preparing direct URL request: %s", err)
  779. }
  780. response, err := httpClient.Do(request)
  781. if err != nil {
  782. return fmt.Errorf("error sending direct URL request: %s", err)
  783. }
  784. defer response.Body.Close()
  785. body, err := ioutil.ReadAll(response.Body)
  786. if err != nil {
  787. return fmt.Errorf("error reading direct URL response: %s", err)
  788. }
  789. if !checkResponse(string(body)) {
  790. return fmt.Errorf("unexpected direct URL response")
  791. }
  792. return nil
  793. }
  794. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  795. if err != nil {
  796. return err
  797. }
  798. // Delay before requesting from external service again
  799. time.Sleep(1 * time.Second)
  800. // Test: use tunneled URL proxy
  801. fetchUsingURLProxyTunneled := func() error {
  802. httpTransport := &http.Transport{
  803. DisableKeepAlives: true,
  804. }
  805. httpClient := &http.Client{
  806. Transport: httpTransport,
  807. Timeout: roundTripTimeout,
  808. }
  809. request, err := http.NewRequest(
  810. "GET",
  811. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  812. httpProxyPort, url.QueryEscape(testUrl)),
  813. nil)
  814. if err != nil {
  815. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  816. }
  817. response, err := httpClient.Do(request)
  818. if err != nil {
  819. return fmt.Errorf("error sending tunneled URL request: %s", err)
  820. }
  821. defer response.Body.Close()
  822. body, err := ioutil.ReadAll(response.Body)
  823. if err != nil {
  824. return fmt.Errorf("error reading tunneled URL response: %s", err)
  825. }
  826. if !checkResponse(string(body)) {
  827. return fmt.Errorf("unexpected tunneled URL response")
  828. }
  829. return nil
  830. }
  831. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  832. if err != nil {
  833. return err
  834. }
  835. return nil
  836. }
  837. func useTunnel(t *testing.T, httpProxyPort int) {
  838. // No action on errors as the tunnel is expected to fail sometimes
  839. testUrl := "https://psiphon3.com"
  840. roundTripTimeout := 1 * time.Second
  841. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  842. if err != nil {
  843. return
  844. }
  845. httpClient := &http.Client{
  846. Transport: &http.Transport{
  847. Proxy: http.ProxyURL(proxyUrl),
  848. },
  849. Timeout: roundTripTimeout,
  850. }
  851. response, err := httpClient.Get(testUrl)
  852. if err != nil {
  853. return
  854. }
  855. response.Body.Close()
  856. }
  857. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  858. // network; for example, the size of the remote server list resource must exceed
  859. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  860. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  861. // too small, the test will take longer to run since more retries are necessary.
  862. //
  863. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  864. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  865. // these test in controller_test serve the dual purpose of ensuring that tunnel
  866. // core works with the production network.
  867. //
  868. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  869. // based on current production network configuration?
  870. const disruptorProxyAddress = "127.0.0.1:2160"
  871. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  872. const disruptorMaxConnectionBytes = 250000
  873. const disruptorMaxConnectionTime = 10 * time.Second
  874. func initDisruptor() {
  875. go func() {
  876. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  877. if err != nil {
  878. fmt.Printf("disruptor proxy listen error: %s\n", err)
  879. return
  880. }
  881. for {
  882. localConn, err := listener.AcceptSocks()
  883. if err != nil {
  884. if e, ok := err.(net.Error); ok && e.Temporary() {
  885. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  886. continue
  887. }
  888. fmt.Printf("disruptor proxy accept error: %s\n", err)
  889. return
  890. }
  891. go func() {
  892. defer localConn.Close()
  893. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  894. if err != nil {
  895. // TODO: log "err" without logging server IPs
  896. fmt.Printf("disruptor proxy dial error\n")
  897. return
  898. }
  899. defer remoteConn.Close()
  900. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  901. if err != nil {
  902. fmt.Printf("disruptor proxy grant error: %s\n", err)
  903. return
  904. }
  905. // Cut connection after disruptorMaxConnectionTime
  906. time.AfterFunc(disruptorMaxConnectionTime, func() {
  907. localConn.Close()
  908. remoteConn.Close()
  909. })
  910. // Relay connection, but only up to disruptorMaxConnectionBytes
  911. waitGroup := new(sync.WaitGroup)
  912. waitGroup.Add(1)
  913. go func() {
  914. defer waitGroup.Done()
  915. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  916. localConn.Close()
  917. remoteConn.Close()
  918. }()
  919. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  920. localConn.Close()
  921. remoteConn.Close()
  922. waitGroup.Wait()
  923. }()
  924. }
  925. }()
  926. }
  927. const upstreamProxyURL = "http://127.0.0.1:2161"
  928. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  929. func hasExpectedCustomHeaders(h http.Header) bool {
  930. for name, values := range upstreamProxyCustomHeaders {
  931. if h[name] == nil {
  932. return false
  933. }
  934. // Order may not be the same
  935. for _, value := range values {
  936. if !common.Contains(h[name], value) {
  937. return false
  938. }
  939. }
  940. }
  941. return true
  942. }
  943. func initUpstreamProxy() {
  944. go func() {
  945. proxy := goproxy.NewProxyHttpServer()
  946. proxy.Logger = log.New(ioutil.Discard, "", 0)
  947. proxy.OnRequest().DoFunc(
  948. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  949. if !hasExpectedCustomHeaders(r.Header) {
  950. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  951. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  952. }
  953. return r, nil
  954. })
  955. proxy.OnRequest().HandleConnectFunc(
  956. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  957. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  958. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  959. return goproxy.RejectConnect, host
  960. }
  961. return goproxy.OkConnect, host
  962. })
  963. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  964. if err != nil {
  965. fmt.Printf("upstream proxy failed: %s\n", err)
  966. }
  967. }()
  968. // TODO: wait until listener is active?
  969. }