controller_test.go 28 KB

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