controller_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. "flag"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "os"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "testing"
  33. "time"
  34. socks "github.com/Psiphon-Inc/goptlib"
  35. )
  36. func TestMain(m *testing.M) {
  37. flag.Parse()
  38. os.Remove(DATA_STORE_FILENAME)
  39. initDisruptor()
  40. setEmitDiagnosticNotices(true)
  41. os.Exit(m.Run())
  42. }
  43. // Note: untunneled upgrade tests must execute before
  44. // the "Run" tests to ensure no tunnel is established.
  45. // We need a way to reset the datastore after it's been
  46. // initialized in order to to clear out its data entries
  47. // and be able to arbitrarily order the tests.
  48. func TestUntunneledUpgradeDownload(t *testing.T) {
  49. doUntunnledUpgradeDownload(t, false)
  50. }
  51. func TestUntunneledResumableUpgradeDownload(t *testing.T) {
  52. doUntunnledUpgradeDownload(t, true)
  53. }
  54. func TestControllerRunSSH(t *testing.T) {
  55. controllerRun(t, TUNNEL_PROTOCOL_SSH, false)
  56. }
  57. func TestControllerRunObfuscatedSSH(t *testing.T) {
  58. controllerRun(t, TUNNEL_PROTOCOL_OBFUSCATED_SSH, false)
  59. }
  60. func TestControllerRunUnfrontedMeek(t *testing.T) {
  61. controllerRun(t, TUNNEL_PROTOCOL_UNFRONTED_MEEK, true)
  62. }
  63. func TestControllerRunFrontedMeek(t *testing.T) {
  64. controllerRun(t, TUNNEL_PROTOCOL_FRONTED_MEEK, true)
  65. }
  66. func TestControllerRunFrontedMeekHTTP(t *testing.T) {
  67. controllerRun(t, TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP, false)
  68. }
  69. func TestControllerRunUnfrontedMeekHTTPS(t *testing.T) {
  70. controllerRun(t, TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS, true)
  71. }
  72. func doUntunnledUpgradeDownload(t *testing.T, disrupt bool) {
  73. configFileContents, err := ioutil.ReadFile("controller_test.config")
  74. if err != nil {
  75. // Skip, don't fail, if config file is not present
  76. t.Skipf("error loading configuration file: %s", err)
  77. }
  78. config, err := LoadConfig(configFileContents)
  79. if err != nil {
  80. t.Fatalf("error processing configuration file: %s", err)
  81. }
  82. if disrupt {
  83. config.UpstreamProxyUrl = disruptorProxyURL
  84. }
  85. // Clear remote server list so tunnel cannot be established and
  86. // untunneled upgrade download case is tested.
  87. config.RemoteServerListUrl = ""
  88. os.Remove(config.UpgradeDownloadFilename)
  89. err = InitDataStore(config)
  90. if err != nil {
  91. t.Fatalf("error initializing datastore: %s", err)
  92. }
  93. controller, err := NewController(config)
  94. if err != nil {
  95. t.Fatalf("error creating controller: %s", err)
  96. }
  97. upgradeDownloaded := make(chan struct{}, 1)
  98. var clientUpgradeDownloadedBytesCount int32
  99. SetNoticeOutput(NewNoticeReceiver(
  100. func(notice []byte) {
  101. // TODO: log notices without logging server IPs:
  102. // fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  103. noticeType, payload, err := GetNotice(notice)
  104. if err != nil {
  105. return
  106. }
  107. switch noticeType {
  108. case "Tunnels":
  109. count := int(payload["count"].(float64))
  110. if count > 0 {
  111. // TODO: wrong goroutine for t.FatalNow()
  112. t.Fatalf("tunnel established unexpectedly")
  113. }
  114. case "ClientUpgradeDownloadedBytes":
  115. atomic.AddInt32(&clientUpgradeDownloadedBytesCount, 1)
  116. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  117. case "ClientUpgradeDownloaded":
  118. select {
  119. case upgradeDownloaded <- *new(struct{}):
  120. default:
  121. }
  122. }
  123. }))
  124. // Run controller
  125. shutdownBroadcast := make(chan struct{})
  126. controllerWaitGroup := new(sync.WaitGroup)
  127. controllerWaitGroup.Add(1)
  128. go func() {
  129. defer controllerWaitGroup.Done()
  130. controller.Run(shutdownBroadcast)
  131. }()
  132. defer func() {
  133. // Test: shutdown must complete within 10 seconds
  134. close(shutdownBroadcast)
  135. shutdownTimeout := time.NewTimer(10 * time.Second)
  136. shutdownOk := make(chan struct{}, 1)
  137. go func() {
  138. controllerWaitGroup.Wait()
  139. shutdownOk <- *new(struct{})
  140. }()
  141. select {
  142. case <-shutdownOk:
  143. case <-shutdownTimeout.C:
  144. t.Fatalf("controller shutdown timeout exceeded")
  145. }
  146. }()
  147. // Test: upgrade must be downloaded within 120 seconds
  148. downloadTimeout := time.NewTimer(120 * time.Second)
  149. select {
  150. case <-upgradeDownloaded:
  151. // TODO: verify downloaded file
  152. case <-downloadTimeout.C:
  153. t.Fatalf("upgrade download timeout exceeded")
  154. }
  155. // Test: with disrupt, must be multiple download progress notices
  156. if disrupt {
  157. count := atomic.LoadInt32(&clientUpgradeDownloadedBytesCount)
  158. if count <= 1 {
  159. t.Fatalf("unexpected upgrade download progress: %d", count)
  160. }
  161. }
  162. }
  163. type TestHostNameTransformer struct {
  164. }
  165. func (TestHostNameTransformer) TransformHostName(string) (string, bool) {
  166. return "example.com", true
  167. }
  168. func controllerRun(t *testing.T, protocol string, protocolUsesHostNameTransformer bool) {
  169. doControllerRun(t, protocol, nil)
  170. if protocolUsesHostNameTransformer {
  171. t.Log("running with testHostNameTransformer")
  172. doControllerRun(t, protocol, &TestHostNameTransformer{})
  173. }
  174. }
  175. func doControllerRun(t *testing.T, protocol string, hostNameTransformer HostNameTransformer) {
  176. configFileContents, err := ioutil.ReadFile("controller_test.config")
  177. if err != nil {
  178. // Skip, don't fail, if config file is not present
  179. t.Skipf("error loading configuration file: %s", err)
  180. }
  181. config, err := LoadConfig(configFileContents)
  182. if err != nil {
  183. t.Fatalf("error processing configuration file: %s", err)
  184. }
  185. // Disable untunneled upgrade downloader to ensure tunneled case is tested
  186. config.UpgradeDownloadClientVersionHeader = ""
  187. os.Remove(config.UpgradeDownloadFilename)
  188. config.TunnelProtocol = protocol
  189. config.HostNameTransformer = hostNameTransformer
  190. err = InitDataStore(config)
  191. if err != nil {
  192. t.Fatalf("error initializing datastore: %s", err)
  193. }
  194. controller, err := NewController(config)
  195. if err != nil {
  196. t.Fatalf("error creating controller: %s", err)
  197. }
  198. // Monitor notices for "Tunnels" with count > 1, the
  199. // indication of tunnel establishment success.
  200. // Also record the selected HTTP proxy port to use
  201. // when fetching websites through the tunnel.
  202. httpProxyPort := 0
  203. tunnelEstablished := make(chan struct{}, 1)
  204. upgradeDownloaded := make(chan struct{}, 1)
  205. SetNoticeOutput(NewNoticeReceiver(
  206. func(notice []byte) {
  207. // TODO: log notices without logging server IPs:
  208. // fmt.Fprintf(os.Stderr, "%s\n", string(notice))
  209. noticeType, payload, err := GetNotice(notice)
  210. if err != nil {
  211. return
  212. }
  213. switch noticeType {
  214. case "Tunnels":
  215. count := int(payload["count"].(float64))
  216. if count > 0 {
  217. select {
  218. case tunnelEstablished <- *new(struct{}):
  219. default:
  220. }
  221. }
  222. case "ClientUpgradeDownloadedBytes":
  223. t.Logf("ClientUpgradeDownloadedBytes: %d", int(payload["bytes"].(float64)))
  224. case "ClientUpgradeDownloaded":
  225. select {
  226. case upgradeDownloaded <- *new(struct{}):
  227. default:
  228. }
  229. case "ListeningHttpProxyPort":
  230. httpProxyPort = int(payload["port"].(float64))
  231. case "ConnectingServer":
  232. serverProtocol := payload["protocol"]
  233. if serverProtocol != protocol {
  234. // TODO: wrong goroutine for t.FatalNow()
  235. t.Fatalf("wrong protocol selected: %s", serverProtocol)
  236. }
  237. }
  238. }))
  239. // Run controller, which establishes tunnels
  240. shutdownBroadcast := make(chan struct{})
  241. controllerWaitGroup := new(sync.WaitGroup)
  242. controllerWaitGroup.Add(1)
  243. go func() {
  244. defer controllerWaitGroup.Done()
  245. controller.Run(shutdownBroadcast)
  246. }()
  247. defer func() {
  248. // Test: shutdown must complete within 10 seconds
  249. close(shutdownBroadcast)
  250. shutdownTimeout := time.NewTimer(10 * time.Second)
  251. shutdownOk := make(chan struct{}, 1)
  252. go func() {
  253. controllerWaitGroup.Wait()
  254. shutdownOk <- *new(struct{})
  255. }()
  256. select {
  257. case <-shutdownOk:
  258. case <-shutdownTimeout.C:
  259. t.Fatalf("controller shutdown timeout exceeded")
  260. }
  261. }()
  262. // Test: tunnel must be established within 60 seconds
  263. establishTimeout := time.NewTimer(60 * time.Second)
  264. select {
  265. case <-tunnelEstablished:
  266. case <-establishTimeout.C:
  267. t.Fatalf("tunnel establish timeout exceeded")
  268. }
  269. // Allow for known race condition described in NewHttpProxy():
  270. time.Sleep(1 * time.Second)
  271. // Test: fetch website through tunnel
  272. fetchWebsite(t, httpProxyPort)
  273. // Test: upgrade must be downloaded within 60 seconds
  274. downloadTimeout := time.NewTimer(60 * time.Second)
  275. select {
  276. case <-upgradeDownloaded:
  277. // TODO: verify downloaded file
  278. case <-downloadTimeout.C:
  279. t.Fatalf("upgrade download timeout exceeded")
  280. }
  281. }
  282. func fetchWebsite(t *testing.T, httpProxyPort int) {
  283. testUrl := "https://raw.githubusercontent.com/Psiphon-Labs/psiphon-tunnel-core/master/LICENSE"
  284. roundTripTimeout := 10 * time.Second
  285. expectedResponsePrefix := " GNU GENERAL PUBLIC LICENSE"
  286. expectedResponseSize := 35148
  287. checkResponse := func(responseBody string) bool {
  288. return strings.HasPrefix(responseBody, expectedResponsePrefix) && len(responseBody) == expectedResponseSize
  289. }
  290. // Test: use HTTP proxy
  291. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", httpProxyPort))
  292. if err != nil {
  293. t.Fatalf("error initializing proxied HTTP request: %s", err)
  294. }
  295. httpClient := &http.Client{
  296. Transport: &http.Transport{
  297. Proxy: http.ProxyURL(proxyUrl),
  298. },
  299. Timeout: roundTripTimeout,
  300. }
  301. response, err := httpClient.Get(testUrl)
  302. if err != nil {
  303. t.Fatalf("error sending proxied HTTP request: %s", err)
  304. }
  305. body, err := ioutil.ReadAll(response.Body)
  306. if err != nil {
  307. t.Fatalf("error reading proxied HTTP response: %s", err)
  308. }
  309. response.Body.Close()
  310. if !checkResponse(string(body)) {
  311. t.Fatalf("unexpected proxied HTTP response")
  312. }
  313. // Test: use direct URL proxy
  314. httpClient = &http.Client{
  315. Transport: http.DefaultTransport,
  316. Timeout: roundTripTimeout,
  317. }
  318. response, err = httpClient.Get(
  319. fmt.Sprintf("http://127.0.0.1:%d/direct/%s",
  320. httpProxyPort, url.QueryEscape(testUrl)))
  321. if err != nil {
  322. t.Fatalf("error sending direct URL request: %s", err)
  323. }
  324. body, err = ioutil.ReadAll(response.Body)
  325. if err != nil {
  326. t.Fatalf("error reading direct URL response: %s", err)
  327. }
  328. response.Body.Close()
  329. if !checkResponse(string(body)) {
  330. t.Fatalf("unexpected direct URL response")
  331. }
  332. // Test: use tunneled URL proxy
  333. response, err = httpClient.Get(
  334. fmt.Sprintf("http://127.0.0.1:%d/tunneled/%s",
  335. httpProxyPort, url.QueryEscape(testUrl)))
  336. if err != nil {
  337. t.Fatalf("error sending tunneled URL request: %s", err)
  338. }
  339. body, err = ioutil.ReadAll(response.Body)
  340. if err != nil {
  341. t.Fatalf("error reading tunneled URL response: %s", err)
  342. }
  343. response.Body.Close()
  344. if !checkResponse(string(body)) {
  345. t.Fatalf("unexpected tunneled URL response")
  346. }
  347. }
  348. const disruptorProxyAddress = "127.0.0.1:2160"
  349. const disruptorProxyURL = "socks4a://" + disruptorProxyAddress
  350. const disruptorMaxConnectionBytes = 2000000
  351. const disruptorMaxConnectionTime = 15 * time.Second
  352. func initDisruptor() {
  353. go func() {
  354. listener, err := socks.ListenSocks("tcp", disruptorProxyAddress)
  355. if err != nil {
  356. fmt.Errorf("disruptor proxy listen error: %s", err)
  357. return
  358. }
  359. for {
  360. localConn, err := listener.AcceptSocks()
  361. if err != nil {
  362. fmt.Errorf("disruptor proxy accept error: %s", err)
  363. return
  364. }
  365. go func() {
  366. defer localConn.Close()
  367. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  368. if err != nil {
  369. fmt.Errorf("disruptor proxy dial error: %s", err)
  370. return
  371. }
  372. defer remoteConn.Close()
  373. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  374. if err != nil {
  375. fmt.Errorf("disruptor proxy grant error: %s", err)
  376. return
  377. }
  378. // Cut connection after disruptorMaxConnectionTime
  379. time.AfterFunc(disruptorMaxConnectionTime, func() {
  380. localConn.Close()
  381. remoteConn.Close()
  382. })
  383. // Relay connection, but only up to disruptorMaxConnectionBytes
  384. waitGroup := new(sync.WaitGroup)
  385. waitGroup.Add(1)
  386. go func() {
  387. defer waitGroup.Done()
  388. io.CopyN(localConn, remoteConn, disruptorMaxConnectionBytes)
  389. }()
  390. io.CopyN(remoteConn, localConn, disruptorMaxConnectionBytes)
  391. waitGroup.Wait()
  392. }()
  393. }
  394. }()
  395. }