controller_test.go 30 KB

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