controller_test.go 30 KB

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