controller_test.go 32 KB

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