controller_test.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. t.Skipf("temporarily disabled")
  415. if !quic.Enabled() {
  416. t.Skip("QUIC is not enabled")
  417. }
  418. controllerRun(t,
  419. &controllerRunConfig{
  420. expectNoServerEntries: false,
  421. protocol: protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH,
  422. clientIsLatestVersion: false,
  423. disableUntunneledUpgrade: true,
  424. disableEstablishing: false,
  425. disableApi: false,
  426. tunnelPoolSize: 1,
  427. useUpstreamProxy: false,
  428. disruptNetwork: false,
  429. transformHostNames: false,
  430. useFragmentor: false,
  431. })
  432. }
  433. type controllerRunConfig struct {
  434. expectNoServerEntries bool
  435. protocol string
  436. clientIsLatestVersion bool
  437. disableUntunneledUpgrade bool
  438. disableEstablishing bool
  439. disableApi bool
  440. tunnelPoolSize int
  441. useUpstreamProxy bool
  442. disruptNetwork bool
  443. transformHostNames bool
  444. useFragmentor bool
  445. }
  446. func controllerRun(t *testing.T, runConfig *controllerRunConfig) {
  447. testDataDirName, err := ioutil.TempDir("", "psiphon-controller-test")
  448. if err != nil {
  449. t.Fatalf("TempDir failed: %s\n", err)
  450. }
  451. defer os.RemoveAll(testDataDirName)
  452. configJSON, err := ioutil.ReadFile("controller_test.config")
  453. if err != nil {
  454. // Skip, don't fail, if config file is not present
  455. t.Skipf("error loading configuration file: %s", err)
  456. }
  457. // Note: a successful tactics request may modify config parameters.
  458. var modifyConfig map[string]interface{}
  459. json.Unmarshal(configJSON, &modifyConfig)
  460. modifyConfig["DataRootDirectory"] = testDataDirName
  461. if runConfig.protocol != "" {
  462. modifyConfig["LimitTunnelProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  463. }
  464. // Override client retry throttle values to speed up automated
  465. // tests and ensure tests complete within fixed deadlines.
  466. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  467. modifyConfig["FetchUpgradeRetryPeriodMilliseconds"] = 250
  468. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  469. if runConfig.disableUntunneledUpgrade {
  470. // Disable untunneled upgrade downloader to ensure tunneled case is tested
  471. modifyConfig["UpgradeDownloadClientVersionHeader"] = "invalid-value"
  472. }
  473. if runConfig.transformHostNames {
  474. modifyConfig["TransformHostNames"] = "always"
  475. } else {
  476. modifyConfig["TransformHostNames"] = "never"
  477. }
  478. if runConfig.useFragmentor {
  479. modifyConfig["UseFragmentor"] = "always"
  480. modifyConfig["FragmentorLimitProtocols"] = protocol.TunnelProtocols{runConfig.protocol}
  481. modifyConfig["FragmentorMinTotalBytes"] = 1000
  482. modifyConfig["FragmentorMaxTotalBytes"] = 2000
  483. modifyConfig["FragmentorMinWriteBytes"] = 1
  484. modifyConfig["FragmentorMaxWriteBytes"] = 100
  485. modifyConfig["FragmentorMinDelayMicroseconds"] = 1000
  486. modifyConfig["FragmentorMaxDelayMicroseconds"] = 10000
  487. modifyConfig["ObfuscatedSSHMinPadding"] = 4096
  488. modifyConfig["ObfuscatedSSHMaxPadding"] = 8192
  489. }
  490. configJSON, _ = json.Marshal(modifyConfig)
  491. config, err := LoadConfig(configJSON)
  492. if err != nil {
  493. t.Fatalf("error processing configuration file: %s", err)
  494. }
  495. if runConfig.clientIsLatestVersion {
  496. config.ClientVersion = "999999999"
  497. }
  498. if runConfig.disableEstablishing {
  499. // Clear remote server list so tunnel cannot be established.
  500. // TODO: also delete all server entries in the datastore.
  501. config.DisableRemoteServerListFetcher = true
  502. }
  503. if runConfig.disableApi {
  504. config.DisableApi = true
  505. }
  506. config.TunnelPoolSize = runConfig.tunnelPoolSize
  507. if runConfig.useUpstreamProxy && runConfig.disruptNetwork {
  508. t.Fatalf("cannot use multiple upstream proxies")
  509. }
  510. if runConfig.disruptNetwork {
  511. config.UpstreamProxyURL = disruptorProxyURL
  512. } else if runConfig.useUpstreamProxy {
  513. config.UpstreamProxyURL = upstreamProxyURL
  514. config.CustomHeaders = upstreamProxyCustomHeaders
  515. }
  516. // All config fields should be set before calling Commit.
  517. err = config.Commit(false)
  518. if err != nil {
  519. t.Fatalf("error committing configuration file: %s", err)
  520. }
  521. err = OpenDataStore(config)
  522. if err != nil {
  523. t.Fatalf("error initializing datastore: %s", err)
  524. }
  525. defer CloseDataStore()
  526. serverEntryCount := CountServerEntries()
  527. if runConfig.expectNoServerEntries && serverEntryCount > 0 {
  528. // TODO: replace expectNoServerEntries with resetServerEntries
  529. // so tests can run in arbitrary order
  530. t.Fatalf("unexpected server entries")
  531. }
  532. controller, err := NewController(config)
  533. if err != nil {
  534. t.Fatalf("error creating controller: %s", err)
  535. }
  536. // Monitor notices for "Tunnels" with count > 1, the
  537. // indication of tunnel establishment success.
  538. // Also record the selected HTTP proxy port to use
  539. // when fetching websites through the tunnel.
  540. httpProxyPort := 0
  541. tunnelEstablished := make(chan struct{}, 1)
  542. upgradeDownloaded := make(chan struct{}, 1)
  543. remoteServerListDownloaded := make(chan struct{}, 1)
  544. confirmedLatestVersion := make(chan struct{}, 1)
  545. var clientUpgradeDownloadedBytesCount int32
  546. var remoteServerListDownloadedBytesCount int32
  547. SetNoticeWriter(NewNoticeReceiver(
  548. func(notice []byte) {
  549. // TODO: log notices without logging server IPs:
  550. //fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  551. noticeType, payload, err := GetNotice(notice)
  552. if err != nil {
  553. return
  554. }
  555. switch noticeType {
  556. case "ListeningHttpProxyPort":
  557. httpProxyPort = int(payload["port"].(float64))
  558. case "ConnectingServer":
  559. serverProtocol := payload["protocol"].(string)
  560. if runConfig.protocol != "" && serverProtocol != runConfig.protocol {
  561. // TODO: wrong goroutine for t.FatalNow()
  562. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  563. }
  564. case "Tunnels":
  565. count := int(payload["count"].(float64))
  566. if count > 0 {
  567. if runConfig.disableEstablishing {
  568. // TODO: wrong goroutine for t.FatalNow()
  569. t.Fatalf("tunnel established unexpectedly")
  570. } else {
  571. select {
  572. case tunnelEstablished <- struct{}{}:
  573. default:
  574. }
  575. }
  576. }
  577. case "ClientUpgradeDownloadedBytes":
  578. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  579. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  580. case "ClientUpgradeDownloaded":
  581. select {
  582. case upgradeDownloaded <- struct{}{}:
  583. default:
  584. }
  585. case "ClientIsLatestVersion":
  586. select {
  587. case confirmedLatestVersion <- struct{}{}:
  588. default:
  589. }
  590. case "RemoteServerListResourceDownloadedBytes":
  591. url := payload["url"].(string)
  592. if url == config.RemoteServerListUrl {
  593. t.Logf("RemoteServerListResourceDownloadedBytes: %d", int(payload["bytes"].(float64)))
  594. atomic.AddInt32(&remoteServerListDownloadedBytesCount, 1)
  595. }
  596. case "RemoteServerListResourceDownloaded":
  597. url := payload["url"].(string)
  598. if url == config.RemoteServerListUrl {
  599. t.Logf("RemoteServerListResourceDownloaded")
  600. select {
  601. case remoteServerListDownloaded <- struct{}{}:
  602. default:
  603. }
  604. }
  605. }
  606. }))
  607. // Run controller, which establishes tunnels
  608. ctx, cancelFunc := context.WithCancel(context.Background())
  609. controllerWaitGroup := new(sync.WaitGroup)
  610. controllerWaitGroup.Add(1)
  611. go func() {
  612. defer controllerWaitGroup.Done()
  613. controller.Run(ctx)
  614. }()
  615. defer func() {
  616. // Test: shutdown must complete within 20 seconds
  617. cancelFunc()
  618. shutdownTimeout := time.NewTimer(20 * time.Second)
  619. shutdownOk := make(chan struct{}, 1)
  620. go func() {
  621. controllerWaitGroup.Wait()
  622. shutdownOk <- struct{}{}
  623. }()
  624. select {
  625. case <-shutdownOk:
  626. case <-shutdownTimeout.C:
  627. t.Fatalf("controller shutdown timeout exceeded")
  628. }
  629. }()
  630. if !runConfig.disableEstablishing {
  631. // Test: tunnel must be established within 120 seconds
  632. establishTimeout := time.NewTimer(120 * time.Second)
  633. select {
  634. case <-tunnelEstablished:
  635. case <-establishTimeout.C:
  636. t.Fatalf("tunnel establish timeout exceeded")
  637. }
  638. // Test: if starting with no server entries, a fetch remote
  639. // server list must have succeeded. With disruptNetwork, the
  640. // fetch must have been resumed at least once.
  641. if serverEntryCount == 0 {
  642. select {
  643. case <-remoteServerListDownloaded:
  644. default:
  645. t.Fatalf("expected remote server list downloaded")
  646. }
  647. if runConfig.disruptNetwork {
  648. count := atomic.LoadInt32(&remoteServerListDownloadedBytesCount)
  649. if count <= 1 {
  650. t.Fatalf("unexpected remote server list download progress: %d", count)
  651. }
  652. }
  653. }
  654. // Cannot establish port forwards in DisableApi mode
  655. if !runConfig.disableApi {
  656. // Test: fetch website through tunnel
  657. // Allow for known race condition described in NewHttpProxy():
  658. time.Sleep(1 * time.Second)
  659. if !runConfig.disruptNetwork {
  660. fetchAndVerifyWebsite(t, httpProxyPort)
  661. }
  662. }
  663. }
  664. // Test: upgrade check/download must be downloaded within 180 seconds
  665. expectUpgrade := !runConfig.disableApi && !runConfig.disableUntunneledUpgrade
  666. if expectUpgrade {
  667. upgradeTimeout := time.NewTimer(120 * time.Second)
  668. select {
  669. case <-upgradeDownloaded:
  670. // TODO: verify downloaded file
  671. if runConfig.clientIsLatestVersion {
  672. t.Fatalf("upgrade downloaded unexpectedly")
  673. }
  674. // Test: with disruptNetwork, must be multiple download progress notices
  675. if runConfig.disruptNetwork {
  676. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  677. if count <= 1 {
  678. t.Fatalf("unexpected upgrade download progress: %d", count)
  679. }
  680. }
  681. case <-confirmedLatestVersion:
  682. if !runConfig.clientIsLatestVersion {
  683. t.Fatalf("confirmed latest version unexpectedly")
  684. }
  685. case <-upgradeTimeout.C:
  686. t.Fatalf("upgrade download timeout exceeded")
  687. }
  688. }
  689. }
  690. func fetchAndVerifyWebsite(t *testing.T, httpProxyPort int) error {
  691. testUrl := "https://psiphon.ca"
  692. roundTripTimeout := 30 * time.Second
  693. expectedResponseContains := "Psiphon"
  694. checkResponse := func(responseBody string) bool {
  695. return strings.Contains(responseBody, expectedResponseContains)
  696. }
  697. // Retries are made to compensate for intermittent failures due
  698. // to external network conditions.
  699. fetchWithRetries := func(fetchName string, fetchFunc func() error) error {
  700. retryCount := 6
  701. retryDelay := 5 * time.Second
  702. var err error
  703. for i := 0; i < retryCount; i++ {
  704. err = fetchFunc()
  705. if err == nil || i == retryCount-1 {
  706. break
  707. }
  708. time.Sleep(retryDelay)
  709. t.Logf("retrying %s...", fetchName)
  710. }
  711. return err
  712. }
  713. // Test: use HTTP proxy
  714. fetchUsingHTTPProxy := func() error {
  715. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  716. if err != nil {
  717. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  718. }
  719. httpTransport := &http.Transport{
  720. Proxy: http.ProxyURL(proxyUrl),
  721. DisableKeepAlives: true,
  722. }
  723. httpClient := &http.Client{
  724. Transport: httpTransport,
  725. Timeout: roundTripTimeout,
  726. }
  727. request, err := http.NewRequest("GET", testUrl, nil)
  728. if err != nil {
  729. return fmt.Errorf("error preparing proxied HTTP request: %s", err)
  730. }
  731. response, err := httpClient.Do(request)
  732. if err != nil {
  733. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  734. }
  735. defer response.Body.Close()
  736. body, err := ioutil.ReadAll(response.Body)
  737. if err != nil {
  738. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  739. }
  740. if !checkResponse(string(body)) {
  741. return fmt.Errorf("unexpected proxied HTTP response")
  742. }
  743. return nil
  744. }
  745. err := fetchWithRetries("proxied HTTP request", fetchUsingHTTPProxy)
  746. if err != nil {
  747. return err
  748. }
  749. // Delay before requesting from external service again
  750. time.Sleep(1 * time.Second)
  751. // Test: use direct URL proxy
  752. fetchUsingURLProxyDirect := func() error {
  753. httpTransport := &http.Transport{
  754. DisableKeepAlives: true,
  755. }
  756. httpClient := &http.Client{
  757. Transport: httpTransport,
  758. Timeout: roundTripTimeout,
  759. }
  760. request, err := http.NewRequest(
  761. "GET",
  762. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  763. httpProxyPort, url.QueryEscape(testUrl)),
  764. nil)
  765. if err != nil {
  766. return fmt.Errorf("error preparing direct URL request: %s", err)
  767. }
  768. response, err := httpClient.Do(request)
  769. if err != nil {
  770. return fmt.Errorf("error sending direct URL request: %s", err)
  771. }
  772. defer response.Body.Close()
  773. body, err := ioutil.ReadAll(response.Body)
  774. if err != nil {
  775. return fmt.Errorf("error reading direct URL response: %s", err)
  776. }
  777. if !checkResponse(string(body)) {
  778. return fmt.Errorf("unexpected direct URL response")
  779. }
  780. return nil
  781. }
  782. err = fetchWithRetries("direct URL request", fetchUsingURLProxyDirect)
  783. if err != nil {
  784. return err
  785. }
  786. // Delay before requesting from external service again
  787. time.Sleep(1 * time.Second)
  788. // Test: use tunneled URL proxy
  789. fetchUsingURLProxyTunneled := func() error {
  790. httpTransport := &http.Transport{
  791. DisableKeepAlives: true,
  792. }
  793. httpClient := &http.Client{
  794. Transport: httpTransport,
  795. Timeout: roundTripTimeout,
  796. }
  797. request, err := http.NewRequest(
  798. "GET",
  799. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  800. httpProxyPort, url.QueryEscape(testUrl)),
  801. nil)
  802. if err != nil {
  803. return fmt.Errorf("error preparing tunneled URL request: %s", err)
  804. }
  805. response, err := httpClient.Do(request)
  806. if err != nil {
  807. return fmt.Errorf("error sending tunneled URL request: %s", err)
  808. }
  809. defer response.Body.Close()
  810. body, err := ioutil.ReadAll(response.Body)
  811. if err != nil {
  812. return fmt.Errorf("error reading tunneled URL response: %s", err)
  813. }
  814. if !checkResponse(string(body)) {
  815. return fmt.Errorf("unexpected tunneled URL response")
  816. }
  817. return nil
  818. }
  819. err = fetchWithRetries("tunneled URL request", fetchUsingURLProxyTunneled)
  820. if err != nil {
  821. return err
  822. }
  823. return nil
  824. }
  825. // Note: Valid values for disruptorMaxConnectionBytes depend on the production
  826. // network; for example, the size of the remote server list resource must exceed
  827. // disruptorMaxConnectionBytes or else TestUntunneledResumableFetchRemoteServerList
  828. // will fail since no retries are required. But if disruptorMaxConnectionBytes is
  829. // too small, the test will take longer to run since more retries are necessary.
  830. //
  831. // Tests such as TestUntunneledResumableFetchRemoteServerList could be rewritten to
  832. // use mock components (for example, see TestObfuscatedRemoteServerLists); however
  833. // these test in controller_test serve the dual purpose of ensuring that tunnel
  834. // core works with the production network.
  835. //
  836. // TODO: set disruptorMaxConnectionBytes (and disruptorMaxConnectionTime) dynamically,
  837. // based on current production network configuration?
  838. const disruptorProxyAddress = "127.0.0.1:2160"
  839. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  840. const disruptorMaxConnectionBytes = 250000
  841. const disruptorMaxConnectionTime = 10 * time.Second
  842. func initDisruptor() {
  843. go func() {
  844. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  845. if err != nil {
  846. fmt.Printf("disruptor proxy listen error: %s\n", err)
  847. return
  848. }
  849. for {
  850. localConn, err := listener.AcceptSocks()
  851. if err != nil {
  852. if e, ok := err.(net.Error); ok && e.Temporary() {
  853. fmt.Printf("disruptor proxy temporary accept error: %s\n", err)
  854. continue
  855. }
  856. fmt.Printf("disruptor proxy accept error: %s\n", err)
  857. return
  858. }
  859. go func() {
  860. defer localConn.Close()
  861. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  862. if err != nil {
  863. // TODO: log "err" without logging server IPs
  864. fmt.Printf("disruptor proxy dial error\n")
  865. return
  866. }
  867. defer remoteConn.Close()
  868. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  869. if err != nil {
  870. fmt.Printf("disruptor proxy grant error: %s\n", err)
  871. return
  872. }
  873. // Cut connection after disruptorMaxConnectionTime
  874. time.AfterFunc(disruptorMaxConnectionTime, func() {
  875. localConn.Close()
  876. remoteConn.Close()
  877. })
  878. // Relay connection, but only up to disruptorMaxConnectionBytes
  879. waitGroup := new(sync.WaitGroup)
  880. waitGroup.Add(1)
  881. go func() {
  882. defer waitGroup.Done()
  883. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  884. localConn.Close()
  885. remoteConn.Close()
  886. }()
  887. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  888. localConn.Close()
  889. remoteConn.Close()
  890. waitGroup.Wait()
  891. }()
  892. }
  893. }()
  894. }
  895. const upstreamProxyURL = "http://testUser:testPassword@127.0.0.1:2161"
  896. var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
  897. func hasExpectedCustomHeaders(h http.Header) bool {
  898. for name, values := range upstreamProxyCustomHeaders {
  899. if h[name] == nil {
  900. return false
  901. }
  902. // Order may not be the same
  903. for _, value := range values {
  904. if !common.Contains(h[name], value) {
  905. return false
  906. }
  907. }
  908. }
  909. return true
  910. }
  911. func initUpstreamProxy() {
  912. go func() {
  913. proxy := goproxy.NewProxyHttpServer()
  914. proxy.Logger = log.New(ioutil.Discard, "", 0)
  915. auth.ProxyBasic(
  916. proxy,
  917. "testRealm",
  918. func(user, passwd string) bool { return user == "testUser" && passwd == "testPassword" })
  919. proxy.OnRequest().DoFunc(
  920. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  921. if !hasExpectedCustomHeaders(r.Header) {
  922. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  923. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  924. }
  925. return r, nil
  926. })
  927. proxy.OnRequest().HandleConnectFunc(
  928. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  929. if !hasExpectedCustomHeaders(ctx.Req.Header) {
  930. fmt.Printf("missing expected headers: %+v\n", ctx.Req.Header)
  931. return goproxy.RejectConnect, host
  932. }
  933. return goproxy.OkConnect, host
  934. })
  935. err := http.ListenAndServe("127.0.0.1:2161", proxy)
  936. if err != nil {
  937. fmt.Printf("upstream proxy failed: %s\n", err)
  938. }
  939. }()
  940. // TODO: wait until listener is active?
  941. }