controller_test.go 30 KB

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