server_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. var err error
  98. serverIPaddress := ""
  99. for _, interfaceName := range []string{"eth0", "en0"} {
  100. serverIPaddress, err = psiphon.GetInterfaceIPAddress(interfaceName)
  101. if err == nil {
  102. break
  103. }
  104. }
  105. if err != nil {
  106. t.Fatalf("error getting server IP address: %s", err)
  107. }
  108. serverConfigJSON, _, encodedServerEntry, err := GenerateConfig(
  109. &GenerateConfigParams{
  110. ServerIPAddress: serverIPaddress,
  111. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  112. WebServerPort: 8000,
  113. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  114. })
  115. if err != nil {
  116. t.Fatalf("error generating server config: %s", err)
  117. }
  118. // customize server config
  119. // Pave psinet with random values to test handshake homepages.
  120. psinetFilename := "psinet.json"
  121. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(t, psinetFilename)
  122. var serverConfig interface{}
  123. json.Unmarshal(serverConfigJSON, &serverConfig)
  124. serverConfig.(map[string]interface{})["GeoIPDatabaseFilename"] = ""
  125. serverConfig.(map[string]interface{})["PsinetDatabaseFilename"] = psinetFilename
  126. serverConfig.(map[string]interface{})["TrafficRulesFilename"] = ""
  127. serverConfigJSON, _ = json.Marshal(serverConfig)
  128. // run server
  129. serverWaitGroup := new(sync.WaitGroup)
  130. serverWaitGroup.Add(1)
  131. go func() {
  132. defer serverWaitGroup.Done()
  133. err := RunServices(serverConfigJSON)
  134. if err != nil {
  135. // TODO: wrong goroutine for t.FatalNow()
  136. t.Fatalf("error running server: %s", err)
  137. }
  138. }()
  139. defer func() {
  140. // Test: orderly server shutdown
  141. p, _ := os.FindProcess(os.Getpid())
  142. p.Signal(os.Interrupt)
  143. shutdownTimeout := time.NewTimer(5 * time.Second)
  144. shutdownOk := make(chan struct{}, 1)
  145. go func() {
  146. serverWaitGroup.Wait()
  147. shutdownOk <- *new(struct{})
  148. }()
  149. select {
  150. case <-shutdownOk:
  151. case <-shutdownTimeout.C:
  152. t.Fatalf("server shutdown timeout exceeded")
  153. }
  154. }()
  155. // Test: hot reload (of psinet)
  156. if runConfig.doHotReload {
  157. // TODO: monitor logs for more robust wait-until-loaded
  158. time.Sleep(1 * time.Second)
  159. // Pave a new psinet with different random values.
  160. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(t, psinetFilename)
  161. p, _ := os.FindProcess(os.Getpid())
  162. p.Signal(syscall.SIGUSR1)
  163. // TODO: monitor logs for more robust wait-until-reloaded
  164. time.Sleep(1 * time.Second)
  165. // After reloading psinet, the new sponsorID/expectedHomepageURL
  166. // should be active, as tested in the client "Homepage" notice
  167. // handler below.
  168. }
  169. // connect to server with client
  170. // TODO: currently, TargetServerEntry only works with one tunnel
  171. numTunnels := 1
  172. localHTTPProxyPort := 8081
  173. establishTunnelPausePeriodSeconds := 1
  174. // Note: calling LoadConfig ensures all *int config fields are initialized
  175. clientConfigJSON := `
  176. {
  177. "ClientVersion" : "0",
  178. "SponsorId" : "0",
  179. "PropagationChannelId" : "0"
  180. }`
  181. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  182. clientConfig.SponsorId = sponsorID
  183. clientConfig.ConnectionWorkerPoolSize = numTunnels
  184. clientConfig.TunnelPoolSize = numTunnels
  185. clientConfig.DisableRemoteServerListFetcher = true
  186. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  187. clientConfig.TargetServerEntry = string(encodedServerEntry)
  188. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  189. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  190. err = psiphon.InitDataStore(clientConfig)
  191. if err != nil {
  192. t.Fatalf("error initializing client datastore: %s", err)
  193. }
  194. controller, err := psiphon.NewController(clientConfig)
  195. if err != nil {
  196. t.Fatalf("error creating client controller: %s", err)
  197. }
  198. tunnelsEstablished := make(chan struct{}, 1)
  199. homepageReceived := make(chan struct{}, 1)
  200. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  201. func(notice []byte) {
  202. //fmt.Printf("%s\n", string(notice))
  203. noticeType, payload, err := psiphon.GetNotice(notice)
  204. if err != nil {
  205. return
  206. }
  207. switch noticeType {
  208. case "Tunnels":
  209. count := int(payload["count"].(float64))
  210. if count >= numTunnels {
  211. select {
  212. case tunnelsEstablished <- *new(struct{}):
  213. default:
  214. }
  215. }
  216. case "Homepage":
  217. homepageURL := payload["url"].(string)
  218. if homepageURL != expectedHomepageURL {
  219. // TODO: wrong goroutine for t.FatalNow()
  220. t.Fatalf("unexpected homepage: %s", homepageURL)
  221. }
  222. select {
  223. case homepageReceived <- *new(struct{}):
  224. default:
  225. }
  226. }
  227. }))
  228. controllerShutdownBroadcast := make(chan struct{})
  229. controllerWaitGroup := new(sync.WaitGroup)
  230. controllerWaitGroup.Add(1)
  231. go func() {
  232. defer controllerWaitGroup.Done()
  233. controller.Run(controllerShutdownBroadcast)
  234. }()
  235. defer func() {
  236. close(controllerShutdownBroadcast)
  237. shutdownTimeout := time.NewTimer(20 * time.Second)
  238. shutdownOk := make(chan struct{}, 1)
  239. go func() {
  240. controllerWaitGroup.Wait()
  241. shutdownOk <- *new(struct{})
  242. }()
  243. select {
  244. case <-shutdownOk:
  245. case <-shutdownTimeout.C:
  246. t.Fatalf("controller shutdown timeout exceeded")
  247. }
  248. }()
  249. // Test: tunnels must be established, and correct homepage
  250. // must be received, within 30 seconds
  251. establishTimeout := time.NewTimer(30 * time.Second)
  252. select {
  253. case <-tunnelsEstablished:
  254. case <-establishTimeout.C:
  255. t.Fatalf("tunnel establish timeout exceeded")
  256. }
  257. select {
  258. case <-homepageReceived:
  259. case <-establishTimeout.C:
  260. t.Fatalf("homepage received timeout exceeded")
  261. }
  262. // Test: tunneled web site fetch
  263. testUrl := "https://psiphon.ca"
  264. roundTripTimeout := 30 * time.Second
  265. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  266. if err != nil {
  267. t.Fatalf("error initializing proxied HTTP request: %s", err)
  268. }
  269. httpClient := &http.Client{
  270. Transport: &http.Transport{
  271. Proxy: http.ProxyURL(proxyUrl),
  272. },
  273. Timeout: roundTripTimeout,
  274. }
  275. response, err := httpClient.Get(testUrl)
  276. if err != nil {
  277. t.Fatalf("error sending proxied HTTP request: %s", err)
  278. }
  279. _, err = ioutil.ReadAll(response.Body)
  280. if err != nil {
  281. t.Fatalf("error reading proxied HTTP response: %s", err)
  282. }
  283. response.Body.Close()
  284. }
  285. func pavePsinetDatabaseFile(t *testing.T, psinetFilename string) (string, string) {
  286. sponsorID, _ := psiphon.MakeRandomStringHex(8)
  287. fakeDomain, _ := psiphon.MakeRandomStringHex(4)
  288. fakePath, _ := psiphon.MakeRandomStringHex(4)
  289. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  290. psinetJSONFormat := `
  291. {
  292. "sponsors": {
  293. "%s": {
  294. "home_pages": {
  295. "None": [
  296. {
  297. "region": null,
  298. "url": "%s"
  299. }
  300. ]
  301. }
  302. }
  303. }
  304. }
  305. `
  306. psinetJSON := fmt.Sprintf(psinetJSONFormat, sponsorID, expectedHomepageURL)
  307. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  308. if err != nil {
  309. t.Fatalf("error paving psinet database: %s", err)
  310. }
  311. return sponsorID, expectedHomepageURL
  312. }