server_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "encoding/json"
  22. "flag"
  23. "fmt"
  24. "io/ioutil"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "sync"
  29. "syscall"
  30. "testing"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. )
  34. func TestMain(m *testing.M) {
  35. flag.Parse()
  36. os.Remove(psiphon.DATA_STORE_FILENAME)
  37. psiphon.SetEmitDiagnosticNotices(true)
  38. os.Exit(m.Run())
  39. }
  40. // Note: not testing fronting meek protocols, which client is
  41. // hard-wired to except running on privileged ports 80 and 443.
  42. func TestSSH(t *testing.T) {
  43. runServer(t,
  44. &runServerConfig{
  45. tunnelProtocol: "SSH",
  46. enableSSHAPIRequests: true,
  47. doHotReload: false,
  48. })
  49. }
  50. func TestOSSH(t *testing.T) {
  51. runServer(t,
  52. &runServerConfig{
  53. tunnelProtocol: "OSSH",
  54. enableSSHAPIRequests: true,
  55. doHotReload: false,
  56. })
  57. }
  58. func TestUnfrontedMeek(t *testing.T) {
  59. runServer(t,
  60. &runServerConfig{
  61. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  62. enableSSHAPIRequests: true,
  63. doHotReload: false,
  64. })
  65. }
  66. func TestUnfrontedMeekHTTPS(t *testing.T) {
  67. runServer(t,
  68. &runServerConfig{
  69. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  70. enableSSHAPIRequests: true,
  71. doHotReload: false,
  72. })
  73. }
  74. func TestWebTransportAPIRequests(t *testing.T) {
  75. runServer(t,
  76. &runServerConfig{
  77. tunnelProtocol: "OSSH",
  78. enableSSHAPIRequests: false,
  79. doHotReload: false,
  80. })
  81. }
  82. func TestHotReload(t *testing.T) {
  83. runServer(t,
  84. &runServerConfig{
  85. tunnelProtocol: "OSSH",
  86. enableSSHAPIRequests: true,
  87. doHotReload: true,
  88. })
  89. }
  90. type runServerConfig struct {
  91. tunnelProtocol string
  92. enableSSHAPIRequests bool
  93. doHotReload bool
  94. }
  95. func runServer(t *testing.T, runConfig *runServerConfig) {
  96. // create a server
  97. serverIPaddress, err := psiphon.GetInterfaceIPAddress("en0")
  98. if err != nil {
  99. t.Fatalf("error getting server IP address: %s", err)
  100. }
  101. serverConfigJSON, _, encodedServerEntry, err := GenerateConfig(
  102. &GenerateConfigParams{
  103. ServerIPAddress: serverIPaddress,
  104. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  105. WebServerPort: 8000,
  106. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  107. })
  108. if err != nil {
  109. t.Fatalf("error generating server config: %s", err)
  110. }
  111. // customize server config
  112. // Pave psinet with random values to test handshake homepages.
  113. psinetFilename := "psinet.json"
  114. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(t, psinetFilename)
  115. var serverConfig interface{}
  116. json.Unmarshal(serverConfigJSON, &serverConfig)
  117. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  118. serverConfig.(map[string]interface{})["PsinetDatabaseFilename"] = psinetFilename
  119. serverConfig.(map[string]interface{})["TrafficRulesFilename"] = ""
  120. serverConfigJSON, _ = json.Marshal(serverConfig)
  121. // run server
  122. serverWaitGroup := new(sync.WaitGroup)
  123. serverWaitGroup.Add(1)
  124. go func() {
  125. defer serverWaitGroup.Done()
  126. err := RunServices(serverConfigJSON)
  127. if err != nil {
  128. // TODO: wrong goroutine for t.FatalNow()
  129. t.Fatalf("error running server: %s", err)
  130. }
  131. }()
  132. defer func() {
  133. // Test: orderly server shutdown
  134. p, _ := os.FindProcess(os.Getpid())
  135. p.Signal(os.Interrupt)
  136. shutdownTimeout := time.NewTimer(5 * time.Second)
  137. shutdownOk := make(chan struct{}, 1)
  138. go func() {
  139. serverWaitGroup.Wait()
  140. shutdownOk <- *new(struct{})
  141. }()
  142. select {
  143. case <-shutdownOk:
  144. case <-shutdownTimeout.C:
  145. t.Fatalf("server shutdown timeout exceeded")
  146. }
  147. }()
  148. // Test: hot reload (of psinet)
  149. if runConfig.doHotReload {
  150. // TODO: monitor logs for more robust wait-until-loaded
  151. time.Sleep(1 * time.Second)
  152. // Pave a new psinet with different random values.
  153. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(t, psinetFilename)
  154. p, _ := os.FindProcess(os.Getpid())
  155. p.Signal(syscall.SIGUSR1)
  156. // TODO: monitor logs for more robust wait-until-reloaded
  157. time.Sleep(1 * time.Second)
  158. // After reloading psinet, the new sponsorID/expectedHomepageURL
  159. // should be active, as tested in the client "Homepage" notice
  160. // handler below.
  161. }
  162. // connect to server with client
  163. // TODO: currently, TargetServerEntry only works with one tunnel
  164. numTunnels := 1
  165. localHTTPProxyPort := 8081
  166. establishTunnelPausePeriodSeconds := 1
  167. // Note: calling LoadConfig ensures all *int config fields are initialized
  168. clientConfigJSON := `
  169. {
  170. "ClientVersion" : "0",
  171. "SponsorId" : "0",
  172. "PropagationChannelId" : "0"
  173. }`
  174. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  175. clientConfig.SponsorId = sponsorID
  176. clientConfig.ConnectionWorkerPoolSize = numTunnels
  177. clientConfig.TunnelPoolSize = numTunnels
  178. clientConfig.DisableRemoteServerListFetcher = true
  179. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  180. clientConfig.TargetServerEntry = string(encodedServerEntry)
  181. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  182. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  183. err = psiphon.InitDataStore(clientConfig)
  184. if err != nil {
  185. t.Fatalf("error initializing client datastore: %s", err)
  186. }
  187. controller, err := psiphon.NewController(clientConfig)
  188. if err != nil {
  189. t.Fatalf("error creating client controller: %s", err)
  190. }
  191. tunnelsEstablished := make(chan struct{}, 1)
  192. homepageReceived := make(chan struct{}, 1)
  193. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  194. func(notice []byte) {
  195. //fmt.Printf("%s\n", string(notice))
  196. noticeType, payload, err := psiphon.GetNotice(notice)
  197. if err != nil {
  198. return
  199. }
  200. switch noticeType {
  201. case "Tunnels":
  202. count := int(payload["count"].(float64))
  203. if count >= numTunnels {
  204. select {
  205. case tunnelsEstablished <- *new(struct{}):
  206. default:
  207. }
  208. }
  209. case "Homepage":
  210. homepageURL := payload["url"].(string)
  211. if homepageURL != expectedHomepageURL {
  212. // TODO: wrong goroutine for t.FatalNow()
  213. t.Fatalf("unexpected homepage: %s", homepageURL)
  214. }
  215. select {
  216. case homepageReceived <- *new(struct{}):
  217. default:
  218. }
  219. }
  220. }))
  221. controllerShutdownBroadcast := make(chan struct{})
  222. controllerWaitGroup := new(sync.WaitGroup)
  223. controllerWaitGroup.Add(1)
  224. go func() {
  225. defer controllerWaitGroup.Done()
  226. controller.Run(controllerShutdownBroadcast)
  227. }()
  228. defer func() {
  229. close(controllerShutdownBroadcast)
  230. shutdownTimeout := time.NewTimer(20 * time.Second)
  231. shutdownOk := make(chan struct{}, 1)
  232. go func() {
  233. controllerWaitGroup.Wait()
  234. shutdownOk <- *new(struct{})
  235. }()
  236. select {
  237. case <-shutdownOk:
  238. case <-shutdownTimeout.C:
  239. t.Fatalf("controller shutdown timeout exceeded")
  240. }
  241. }()
  242. // Test: tunnels must be established, and correct homepage
  243. // must be received, within 30 seconds
  244. establishTimeout := time.NewTimer(30 * time.Second)
  245. select {
  246. case <-tunnelsEstablished:
  247. case <-establishTimeout.C:
  248. t.Fatalf("tunnel establish timeout exceeded")
  249. }
  250. select {
  251. case <-homepageReceived:
  252. case <-establishTimeout.C:
  253. t.Fatalf("homepage received timeout exceeded")
  254. }
  255. // Test: tunneled web site fetch
  256. testUrl := "https://psiphon.ca"
  257. roundTripTimeout := 30 * time.Second
  258. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  259. if err != nil {
  260. t.Fatalf("error initializing proxied HTTP request: %s", err)
  261. }
  262. httpClient := &http.Client{
  263. Transport: &http.Transport{
  264. Proxy: http.ProxyURL(proxyUrl),
  265. },
  266. Timeout: roundTripTimeout,
  267. }
  268. response, err := httpClient.Get(testUrl)
  269. if err != nil {
  270. t.Fatalf("error sending proxied HTTP request: %s", err)
  271. }
  272. _, err = ioutil.ReadAll(response.Body)
  273. if err != nil {
  274. t.Fatalf("error reading proxied HTTP response: %s", err)
  275. }
  276. response.Body.Close()
  277. }
  278. func pavePsinetDatabaseFile(t *testing.T, psinetFilename string) (string, string) {
  279. sponsorID, _ := psiphon.MakeRandomStringHex(8)
  280. fakeDomain, _ := psiphon.MakeRandomStringHex(4)
  281. fakePath, _ := psiphon.MakeRandomStringHex(4)
  282. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  283. psinetJSONFormat := `
  284. {
  285. "sponsors": {
  286. "%s": {
  287. "home_pages": {
  288. "None": [
  289. {
  290. "region": null,
  291. "url": "%s"
  292. }
  293. ]
  294. }
  295. }
  296. }
  297. }
  298. `
  299. psinetJSON := fmt.Sprintf(psinetJSONFormat, sponsorID, expectedHomepageURL)
  300. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  301. if err != nil {
  302. t.Fatalf("error paving psinet database: %s", err)
  303. }
  304. return sponsorID, expectedHomepageURL
  305. }