controller_test.go 34 KB

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