server_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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. "context"
  22. "encoding/json"
  23. "errors"
  24. "flag"
  25. "fmt"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "os"
  31. "path/filepath"
  32. "strconv"
  33. "sync"
  34. "syscall"
  35. "testing"
  36. "time"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "golang.org/x/net/proxy"
  44. )
  45. var serverIPAddress, testDataDirName string
  46. var mockWebServerURL, mockWebServerExpectedResponse string
  47. var mockWebServerPort = 8080
  48. func TestMain(m *testing.M) {
  49. flag.Parse()
  50. var err error
  51. for _, interfaceName := range []string{"eth0", "en0"} {
  52. var serverIPv4Address, serverIPv6Address net.IP
  53. serverIPv4Address, serverIPv6Address, err = common.GetInterfaceIPAddresses(interfaceName)
  54. if err == nil {
  55. if serverIPv4Address != nil {
  56. serverIPAddress = serverIPv4Address.String()
  57. } else {
  58. serverIPAddress = serverIPv6Address.String()
  59. }
  60. break
  61. }
  62. }
  63. if err != nil {
  64. fmt.Printf("error getting server IP address: %s", err)
  65. os.Exit(1)
  66. }
  67. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  68. if err != nil {
  69. fmt.Printf("TempDir failed: %s\n", err)
  70. os.Exit(1)
  71. }
  72. defer os.RemoveAll(testDataDirName)
  73. os.Remove(filepath.Join(testDataDirName, psiphon.DATA_STORE_FILENAME))
  74. psiphon.SetEmitDiagnosticNotices(true)
  75. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  76. os.Exit(m.Run())
  77. }
  78. func runMockWebServer() (string, string) {
  79. responseBody, _ := common.MakeSecureRandomStringHex(100000)
  80. serveMux := http.NewServeMux()
  81. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  82. w.Write([]byte(responseBody))
  83. })
  84. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  85. server := &http.Server{
  86. Addr: webServerAddress,
  87. Handler: serveMux,
  88. }
  89. go func() {
  90. err := server.ListenAndServe()
  91. if err != nil {
  92. fmt.Printf("error running mock web server: %s\n", err)
  93. os.Exit(1)
  94. }
  95. }()
  96. // TODO: properly synchronize with web server readiness
  97. time.Sleep(1 * time.Second)
  98. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  99. }
  100. // Note: not testing fronting meek protocols, which client is
  101. // hard-wired to except running on privileged ports 80 and 443.
  102. func TestSSH(t *testing.T) {
  103. runServer(t,
  104. &runServerConfig{
  105. tunnelProtocol: "SSH",
  106. enableSSHAPIRequests: true,
  107. doHotReload: false,
  108. doDefaultSponsorID: false,
  109. denyTrafficRules: false,
  110. requireAuthorization: true,
  111. omitAuthorization: false,
  112. doTunneledWebRequest: true,
  113. doTunneledNTPRequest: true,
  114. })
  115. }
  116. func TestOSSH(t *testing.T) {
  117. runServer(t,
  118. &runServerConfig{
  119. tunnelProtocol: "OSSH",
  120. enableSSHAPIRequests: true,
  121. doHotReload: false,
  122. doDefaultSponsorID: false,
  123. denyTrafficRules: false,
  124. requireAuthorization: true,
  125. omitAuthorization: false,
  126. doTunneledWebRequest: true,
  127. doTunneledNTPRequest: true,
  128. })
  129. }
  130. func TestUnfrontedMeek(t *testing.T) {
  131. runServer(t,
  132. &runServerConfig{
  133. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  134. enableSSHAPIRequests: true,
  135. doHotReload: false,
  136. doDefaultSponsorID: false,
  137. denyTrafficRules: false,
  138. requireAuthorization: true,
  139. omitAuthorization: false,
  140. doTunneledWebRequest: true,
  141. doTunneledNTPRequest: true,
  142. })
  143. }
  144. func TestUnfrontedMeekHTTPS(t *testing.T) {
  145. runServer(t,
  146. &runServerConfig{
  147. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  148. enableSSHAPIRequests: true,
  149. doHotReload: false,
  150. doDefaultSponsorID: false,
  151. denyTrafficRules: false,
  152. requireAuthorization: true,
  153. omitAuthorization: false,
  154. doTunneledWebRequest: true,
  155. doTunneledNTPRequest: true,
  156. })
  157. }
  158. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  159. runServer(t,
  160. &runServerConfig{
  161. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  162. enableSSHAPIRequests: true,
  163. doHotReload: false,
  164. doDefaultSponsorID: false,
  165. denyTrafficRules: false,
  166. requireAuthorization: true,
  167. omitAuthorization: false,
  168. doTunneledWebRequest: true,
  169. doTunneledNTPRequest: true,
  170. })
  171. }
  172. func TestWebTransportAPIRequests(t *testing.T) {
  173. runServer(t,
  174. &runServerConfig{
  175. tunnelProtocol: "OSSH",
  176. enableSSHAPIRequests: false,
  177. doHotReload: false,
  178. doDefaultSponsorID: false,
  179. denyTrafficRules: false,
  180. requireAuthorization: false,
  181. omitAuthorization: true,
  182. doTunneledWebRequest: true,
  183. doTunneledNTPRequest: true,
  184. })
  185. }
  186. func TestHotReload(t *testing.T) {
  187. runServer(t,
  188. &runServerConfig{
  189. tunnelProtocol: "OSSH",
  190. enableSSHAPIRequests: true,
  191. doHotReload: true,
  192. doDefaultSponsorID: false,
  193. denyTrafficRules: false,
  194. requireAuthorization: true,
  195. omitAuthorization: false,
  196. doTunneledWebRequest: true,
  197. doTunneledNTPRequest: true,
  198. })
  199. }
  200. func TestDefaultSessionID(t *testing.T) {
  201. runServer(t,
  202. &runServerConfig{
  203. tunnelProtocol: "OSSH",
  204. enableSSHAPIRequests: true,
  205. doHotReload: true,
  206. doDefaultSponsorID: true,
  207. denyTrafficRules: false,
  208. requireAuthorization: true,
  209. omitAuthorization: false,
  210. doTunneledWebRequest: true,
  211. doTunneledNTPRequest: true,
  212. })
  213. }
  214. func TestDenyTrafficRules(t *testing.T) {
  215. runServer(t,
  216. &runServerConfig{
  217. tunnelProtocol: "OSSH",
  218. enableSSHAPIRequests: true,
  219. doHotReload: true,
  220. doDefaultSponsorID: false,
  221. denyTrafficRules: true,
  222. requireAuthorization: true,
  223. omitAuthorization: false,
  224. doTunneledWebRequest: true,
  225. doTunneledNTPRequest: true,
  226. })
  227. }
  228. func TestOmitAuthorization(t *testing.T) {
  229. runServer(t,
  230. &runServerConfig{
  231. tunnelProtocol: "OSSH",
  232. enableSSHAPIRequests: true,
  233. doHotReload: true,
  234. doDefaultSponsorID: false,
  235. denyTrafficRules: false,
  236. requireAuthorization: true,
  237. omitAuthorization: true,
  238. doTunneledWebRequest: true,
  239. doTunneledNTPRequest: true,
  240. })
  241. }
  242. func TestNoAuthorization(t *testing.T) {
  243. runServer(t,
  244. &runServerConfig{
  245. tunnelProtocol: "OSSH",
  246. enableSSHAPIRequests: true,
  247. doHotReload: true,
  248. doDefaultSponsorID: false,
  249. denyTrafficRules: false,
  250. requireAuthorization: false,
  251. omitAuthorization: true,
  252. doTunneledWebRequest: true,
  253. doTunneledNTPRequest: true,
  254. })
  255. }
  256. func TestUnusedAuthorization(t *testing.T) {
  257. runServer(t,
  258. &runServerConfig{
  259. tunnelProtocol: "OSSH",
  260. enableSSHAPIRequests: true,
  261. doHotReload: true,
  262. doDefaultSponsorID: false,
  263. denyTrafficRules: false,
  264. requireAuthorization: false,
  265. omitAuthorization: false,
  266. doTunneledWebRequest: true,
  267. doTunneledNTPRequest: true,
  268. })
  269. }
  270. func TestTCPOnlySLOK(t *testing.T) {
  271. runServer(t,
  272. &runServerConfig{
  273. tunnelProtocol: "OSSH",
  274. enableSSHAPIRequests: true,
  275. doHotReload: false,
  276. doDefaultSponsorID: false,
  277. denyTrafficRules: false,
  278. requireAuthorization: true,
  279. omitAuthorization: false,
  280. doTunneledWebRequest: true,
  281. doTunneledNTPRequest: false,
  282. })
  283. }
  284. func TestUDPOnlySLOK(t *testing.T) {
  285. runServer(t,
  286. &runServerConfig{
  287. tunnelProtocol: "OSSH",
  288. enableSSHAPIRequests: true,
  289. doHotReload: false,
  290. doDefaultSponsorID: false,
  291. denyTrafficRules: false,
  292. requireAuthorization: true,
  293. omitAuthorization: false,
  294. doTunneledWebRequest: false,
  295. doTunneledNTPRequest: true,
  296. })
  297. }
  298. type runServerConfig struct {
  299. tunnelProtocol string
  300. enableSSHAPIRequests bool
  301. doHotReload bool
  302. doDefaultSponsorID bool
  303. denyTrafficRules bool
  304. requireAuthorization bool
  305. omitAuthorization bool
  306. doTunneledWebRequest bool
  307. doTunneledNTPRequest bool
  308. }
  309. func runServer(t *testing.T, runConfig *runServerConfig) {
  310. // configure authorized access
  311. accessType := "test-access-type"
  312. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  313. if err != nil {
  314. t.Fatalf("error creating access control key pair: %s", err)
  315. }
  316. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  317. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  318. }
  319. var authorizationID [32]byte
  320. clientAuthorization, err := accesscontrol.IssueAuthorization(
  321. accessControlSigningKey,
  322. authorizationID[:],
  323. time.Now().Add(1*time.Hour))
  324. if err != nil {
  325. t.Fatalf("error issuing authorization: %s", err)
  326. }
  327. // Enable tactics when the test protocol is meek. Both the client and the
  328. // server will be configured to support tactics. The client config will be
  329. // set with a nonfunctional config so that the tactics request must
  330. // succeed, overriding the nonfunctional values, for the tunnel to
  331. // establish.
  332. doTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  333. // All servers require a tactics config with valid keys.
  334. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  335. tactics.GenerateKeys()
  336. if err != nil {
  337. t.Fatalf("error generating tactics keys: %s", err)
  338. }
  339. // create a server
  340. generateConfigParams := &GenerateConfigParams{
  341. ServerIPAddress: serverIPAddress,
  342. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  343. WebServerPort: 8000,
  344. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  345. }
  346. if doTactics {
  347. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  348. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  349. }
  350. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  351. if err != nil {
  352. t.Fatalf("error generating server config: %s", err)
  353. }
  354. // customize server config
  355. // Pave psinet with random values to test handshake homepages.
  356. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  357. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  358. t, runConfig.doDefaultSponsorID, psinetFilename)
  359. // Pave OSL config for SLOK testing
  360. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  361. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  362. // Pave traffic rules file which exercises handshake parameter filtering. Client
  363. // must handshake with specified sponsor ID in order to allow ports for tunneled
  364. // requests.
  365. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  366. paveTrafficRulesFile(
  367. t, trafficRulesFilename, propagationChannelID, accessType,
  368. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  369. var tacticsConfigFilename string
  370. // Only pave the tactics config when tactics are required. This exercises the
  371. // case where the tactics config is omitted.
  372. if doTactics {
  373. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  374. paveTacticsConfigFile(
  375. t, tacticsConfigFilename,
  376. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  377. runConfig.tunnelProtocol,
  378. propagationChannelID)
  379. }
  380. var serverConfig map[string]interface{}
  381. json.Unmarshal(serverConfigJSON, &serverConfig)
  382. serverConfig["GeoIPDatabaseFilename"] = ""
  383. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  384. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  385. serverConfig["OSLConfigFilename"] = oslConfigFilename
  386. if doTactics {
  387. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  388. }
  389. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  390. serverConfig["LogLevel"] = "debug"
  391. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  392. // Set this parameter so at least the semaphore functions are called.
  393. // TODO: test that the concurrency limit is correctly enforced.
  394. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  395. // Exercise this option.
  396. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  397. serverConfigJSON, _ = json.Marshal(serverConfig)
  398. // run server
  399. serverWaitGroup := new(sync.WaitGroup)
  400. serverWaitGroup.Add(1)
  401. go func() {
  402. defer serverWaitGroup.Done()
  403. err := RunServices(serverConfigJSON)
  404. if err != nil {
  405. // TODO: wrong goroutine for t.FatalNow()
  406. t.Fatalf("error running server: %s", err)
  407. }
  408. }()
  409. defer func() {
  410. // Test: orderly server shutdown
  411. p, _ := os.FindProcess(os.Getpid())
  412. p.Signal(os.Interrupt)
  413. shutdownTimeout := time.NewTimer(5 * time.Second)
  414. shutdownOk := make(chan struct{}, 1)
  415. go func() {
  416. serverWaitGroup.Wait()
  417. shutdownOk <- *new(struct{})
  418. }()
  419. select {
  420. case <-shutdownOk:
  421. case <-shutdownTimeout.C:
  422. t.Fatalf("server shutdown timeout exceeded")
  423. }
  424. }()
  425. // TODO: monitor logs for more robust wait-until-loaded
  426. time.Sleep(1 * time.Second)
  427. // Test: hot reload (of psinet and traffic rules)
  428. if runConfig.doHotReload {
  429. // Pave new config files with different random values.
  430. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  431. t, runConfig.doDefaultSponsorID, psinetFilename)
  432. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  433. paveTrafficRulesFile(
  434. t, trafficRulesFilename, propagationChannelID, accessType,
  435. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  436. p, _ := os.FindProcess(os.Getpid())
  437. p.Signal(syscall.SIGUSR1)
  438. // TODO: monitor logs for more robust wait-until-reloaded
  439. time.Sleep(1 * time.Second)
  440. // After reloading psinet, the new sponsorID/expectedHomepageURL
  441. // should be active, as tested in the client "Homepage" notice
  442. // handler below.
  443. }
  444. // Exercise server_load logging
  445. p, _ := os.FindProcess(os.Getpid())
  446. p.Signal(syscall.SIGUSR2)
  447. // connect to server with client
  448. // TODO: currently, TargetServerEntry only works with one tunnel
  449. numTunnels := 1
  450. localSOCKSProxyPort := 1081
  451. localHTTPProxyPort := 8081
  452. jsonNetworkID := ""
  453. if doTactics {
  454. // Use a distinct prefix for network ID for each test run to
  455. // ensure tactics from different runs don't apply; this is
  456. // a workaround for the singleton datastore.
  457. prefix := time.Now().String()
  458. jsonNetworkID = fmt.Sprintf(`,"NetworkID" : "%s-%s"`, prefix, "NETWORK1")
  459. }
  460. clientConfigJSON := fmt.Sprintf(`
  461. {
  462. "ClientPlatform" : "Windows",
  463. "ClientVersion" : "0",
  464. "SponsorId" : "0",
  465. "PropagationChannelId" : "0",
  466. "DisableRemoteServerListFetcher" : true,
  467. "UseIndistinguishableTLS" : true,
  468. "EstablishTunnelPausePeriodSeconds" : 1,
  469. "ConnectionWorkerPoolSize" : %d,
  470. "TunnelProtocols" : ["%s"]
  471. %s
  472. }`, numTunnels, runConfig.tunnelProtocol, jsonNetworkID)
  473. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  474. if err != nil {
  475. t.Fatalf("error processing configuration file: %s", err)
  476. }
  477. clientConfig.DataStoreDirectory = testDataDirName
  478. if !runConfig.doDefaultSponsorID {
  479. clientConfig.SponsorId = sponsorID
  480. }
  481. clientConfig.PropagationChannelId = propagationChannelID
  482. clientConfig.TunnelPoolSize = numTunnels
  483. clientConfig.TargetServerEntry = string(encodedServerEntry)
  484. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  485. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  486. clientConfig.EmitSLOKs = true
  487. if !runConfig.omitAuthorization {
  488. clientConfig.Authorizations = []string{clientAuthorization}
  489. }
  490. err = clientConfig.Commit()
  491. if err != nil {
  492. t.Fatalf("error committing configuration file: %s", err)
  493. }
  494. if doTactics {
  495. // Configure nonfunctional values that must be overridden by tactics.
  496. applyParameters := make(map[string]interface{})
  497. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  498. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  499. err = clientConfig.SetClientParameters("", true, applyParameters)
  500. if err != nil {
  501. t.Fatalf("SetClientParameters failed: %s", err)
  502. }
  503. }
  504. err = psiphon.InitDataStore(clientConfig)
  505. if err != nil {
  506. t.Fatalf("error initializing client datastore: %s", err)
  507. }
  508. psiphon.DeleteSLOKs()
  509. controller, err := psiphon.NewController(clientConfig)
  510. if err != nil {
  511. t.Fatalf("error creating client controller: %s", err)
  512. }
  513. tunnelsEstablished := make(chan struct{}, 1)
  514. homepageReceived := make(chan struct{}, 1)
  515. slokSeeded := make(chan struct{}, 1)
  516. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  517. func(notice []byte) {
  518. //fmt.Printf("%s\n", string(notice))
  519. noticeType, payload, err := psiphon.GetNotice(notice)
  520. if err != nil {
  521. return
  522. }
  523. switch noticeType {
  524. case "Tunnels":
  525. count := int(payload["count"].(float64))
  526. if count >= numTunnels {
  527. sendNotificationReceived(tunnelsEstablished)
  528. }
  529. case "Homepage":
  530. homepageURL := payload["url"].(string)
  531. if homepageURL != expectedHomepageURL {
  532. // TODO: wrong goroutine for t.FatalNow()
  533. t.Fatalf("unexpected homepage: %s", homepageURL)
  534. }
  535. sendNotificationReceived(homepageReceived)
  536. case "SLOKSeeded":
  537. sendNotificationReceived(slokSeeded)
  538. }
  539. }))
  540. ctx, cancelFunc := context.WithCancel(context.Background())
  541. controllerWaitGroup := new(sync.WaitGroup)
  542. controllerWaitGroup.Add(1)
  543. go func() {
  544. defer controllerWaitGroup.Done()
  545. controller.Run(ctx)
  546. }()
  547. defer func() {
  548. cancelFunc()
  549. shutdownTimeout := time.NewTimer(20 * time.Second)
  550. shutdownOk := make(chan struct{}, 1)
  551. go func() {
  552. controllerWaitGroup.Wait()
  553. shutdownOk <- *new(struct{})
  554. }()
  555. select {
  556. case <-shutdownOk:
  557. case <-shutdownTimeout.C:
  558. t.Fatalf("controller shutdown timeout exceeded")
  559. }
  560. }()
  561. // Test: tunnels must be established, and correct homepage
  562. // must be received, within 30 seconds
  563. timeoutSignal := make(chan struct{})
  564. go func() {
  565. timer := time.NewTimer(30 * time.Second)
  566. <-timer.C
  567. close(timeoutSignal)
  568. }()
  569. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  570. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  571. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  572. if runConfig.doTunneledWebRequest {
  573. // Test: tunneled web site fetch
  574. err = makeTunneledWebRequest(
  575. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  576. if err == nil {
  577. if expectTrafficFailure {
  578. t.Fatalf("unexpected tunneled web request success")
  579. }
  580. } else {
  581. if !expectTrafficFailure {
  582. t.Fatalf("tunneled web request failed: %s", err)
  583. }
  584. }
  585. }
  586. if runConfig.doTunneledNTPRequest {
  587. // Test: tunneled UDP packets
  588. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  589. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  590. if err == nil {
  591. if expectTrafficFailure {
  592. t.Fatalf("unexpected tunneled NTP request success")
  593. }
  594. } else {
  595. if !expectTrafficFailure {
  596. t.Fatalf("tunneled NTP request failed: %s", err)
  597. }
  598. }
  599. }
  600. // Test: await SLOK payload
  601. if !expectTrafficFailure {
  602. time.Sleep(1 * time.Second)
  603. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  604. numSLOKs := psiphon.CountSLOKs()
  605. if numSLOKs != expectedNumSLOKs {
  606. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  607. }
  608. }
  609. }
  610. func makeTunneledWebRequest(
  611. t *testing.T,
  612. localHTTPProxyPort int,
  613. requestURL, expectedResponseBody string) error {
  614. roundTripTimeout := 30 * time.Second
  615. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  616. if err != nil {
  617. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  618. }
  619. httpClient := &http.Client{
  620. Transport: &http.Transport{
  621. Proxy: http.ProxyURL(proxyUrl),
  622. },
  623. Timeout: roundTripTimeout,
  624. }
  625. response, err := httpClient.Get(requestURL)
  626. if err != nil {
  627. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  628. }
  629. body, err := ioutil.ReadAll(response.Body)
  630. if err != nil {
  631. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  632. }
  633. response.Body.Close()
  634. if string(body) != expectedResponseBody {
  635. return fmt.Errorf("unexpected proxied HTTP response")
  636. }
  637. return nil
  638. }
  639. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  640. timeout := 20 * time.Second
  641. var err error
  642. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  643. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  644. if err == nil {
  645. break
  646. }
  647. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  648. }
  649. return err
  650. }
  651. var nextUDPProxyPort = 7300
  652. func makeTunneledNTPRequestAttempt(
  653. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  654. nextUDPProxyPort++
  655. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  656. if err != nil {
  657. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  658. }
  659. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  660. // handles it, and then terminates.
  661. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  662. if waitGroup != nil {
  663. defer waitGroup.Done()
  664. }
  665. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  666. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  667. if err != nil {
  668. t.Logf("ListenUDP for %s failed: %s", destination, err)
  669. return
  670. }
  671. defer serverUDPConn.Close()
  672. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  673. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  674. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  675. buffer[udpgwPreambleSize:])
  676. if err != nil {
  677. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  678. return
  679. }
  680. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  681. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  682. if err != nil {
  683. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  684. return
  685. }
  686. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  687. if err != nil {
  688. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  689. return
  690. }
  691. defer socksTCPConn.Close()
  692. flags := uint8(0)
  693. if destinationPort == 53 {
  694. flags = udpgwProtocolFlagDNS
  695. }
  696. err = writeUdpgwPreamble(
  697. udpgwPreambleSize,
  698. flags,
  699. 0,
  700. destinationIP,
  701. destinationPort,
  702. uint16(packetSize),
  703. buffer)
  704. if err != nil {
  705. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  706. return
  707. }
  708. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  709. if err != nil {
  710. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  711. return
  712. }
  713. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  714. if err != nil {
  715. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  716. return
  717. }
  718. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  719. if err != nil {
  720. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  721. return
  722. }
  723. }
  724. // Tunneled DNS request
  725. waitGroup := new(sync.WaitGroup)
  726. waitGroup.Add(1)
  727. go localUDPProxy(
  728. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  729. 53,
  730. waitGroup)
  731. // TODO: properly synchronize with local UDP proxy startup
  732. time.Sleep(1 * time.Second)
  733. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  734. if err != nil {
  735. return fmt.Errorf("DialUDP failed: %s", err)
  736. }
  737. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  738. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  739. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  740. clientUDPConn.Close()
  741. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  742. err = errors.New("no address")
  743. }
  744. if err != nil {
  745. return fmt.Errorf("ResolveIP failed: %s", err)
  746. }
  747. waitGroup.Wait()
  748. // Tunneled NTP request
  749. waitGroup = new(sync.WaitGroup)
  750. waitGroup.Add(1)
  751. go localUDPProxy(
  752. addrs[0][len(addrs[0])-4:],
  753. 123,
  754. waitGroup)
  755. // TODO: properly synchronize with local UDP proxy startup
  756. time.Sleep(1 * time.Second)
  757. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  758. if err != nil {
  759. return fmt.Errorf("DialUDP failed: %s", err)
  760. }
  761. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  762. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  763. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  764. ntpData := make([]byte, 48)
  765. ntpData[0] = 3<<3 | 3
  766. _, err = clientUDPConn.Write(ntpData)
  767. if err != nil {
  768. clientUDPConn.Close()
  769. return fmt.Errorf("NTP Write failed: %s", err)
  770. }
  771. _, err = clientUDPConn.Read(ntpData)
  772. if err != nil {
  773. clientUDPConn.Close()
  774. return fmt.Errorf("NTP Read failed: %s", err)
  775. }
  776. clientUDPConn.Close()
  777. var sec, frac uint64
  778. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  779. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  780. nsec := sec * 1e9
  781. nsec += (frac * 1e9) >> 32
  782. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  783. now := time.Now()
  784. diff := ntpNow.Sub(now)
  785. if diff < 0 {
  786. diff = -diff
  787. }
  788. if diff > 1*time.Minute {
  789. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  790. }
  791. waitGroup.Wait()
  792. return nil
  793. }
  794. func pavePsinetDatabaseFile(
  795. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  796. sponsorID, _ := common.MakeSecureRandomStringHex(8)
  797. fakeDomain, _ := common.MakeSecureRandomStringHex(4)
  798. fakePath, _ := common.MakeSecureRandomStringHex(4)
  799. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  800. psinetJSONFormat := `
  801. {
  802. "default_sponsor_id" : "%s",
  803. "sponsors": {
  804. "%s": {
  805. "home_pages": {
  806. "None": [
  807. {
  808. "region": null,
  809. "url": "%s"
  810. }
  811. ]
  812. }
  813. }
  814. }
  815. }
  816. `
  817. defaultSponsorID := ""
  818. if useDefaultSponsorID {
  819. defaultSponsorID = sponsorID
  820. }
  821. psinetJSON := fmt.Sprintf(
  822. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  823. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  824. if err != nil {
  825. t.Fatalf("error paving psinet database file: %s", err)
  826. }
  827. return sponsorID, expectedHomepageURL
  828. }
  829. func paveTrafficRulesFile(
  830. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  831. requireAuthorization, deny bool) {
  832. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  833. allowUDPPorts := "53, 123"
  834. if deny {
  835. allowTCPPorts = "0"
  836. allowUDPPorts = "0"
  837. }
  838. authorizationFilterFormat := `,
  839. "AuthorizedAccessTypes" : ["%s"]
  840. `
  841. authorizationFilter := ""
  842. if requireAuthorization {
  843. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  844. }
  845. trafficRulesJSONFormat := `
  846. {
  847. "DefaultRules" : {
  848. "RateLimits" : {
  849. "ReadBytesPerSecond": 16384,
  850. "WriteBytesPerSecond": 16384
  851. },
  852. "AllowTCPPorts" : [0],
  853. "AllowUDPPorts" : [0]
  854. },
  855. "FilteredRules" : [
  856. {
  857. "Filter" : {
  858. "HandshakeParameters" : {
  859. "propagation_channel_id" : ["%s"]
  860. }%s
  861. },
  862. "Rules" : {
  863. "RateLimits" : {
  864. "ReadUnthrottledBytes": 132352,
  865. "WriteUnthrottledBytes": 132352
  866. },
  867. "AllowTCPPorts" : [%s],
  868. "AllowUDPPorts" : [%s]
  869. }
  870. }
  871. ]
  872. }
  873. `
  874. trafficRulesJSON := fmt.Sprintf(
  875. trafficRulesJSONFormat, propagationChannelID, authorizationFilter, allowTCPPorts, allowUDPPorts)
  876. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  877. if err != nil {
  878. t.Fatalf("error paving traffic rules file: %s", err)
  879. }
  880. }
  881. var expectedNumSLOKs = 3
  882. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  883. oslConfigJSONFormat := `
  884. {
  885. "Schemes" : [
  886. {
  887. "Epoch" : "%s",
  888. "Regions" : [],
  889. "PropagationChannelIDs" : ["%s"],
  890. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  891. "SeedSpecs" : [
  892. {
  893. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  894. "UpstreamSubnets" : ["0.0.0.0/0"],
  895. "Targets" :
  896. {
  897. "BytesRead" : 1,
  898. "BytesWritten" : 1,
  899. "PortForwardDurationNanoseconds" : 1
  900. }
  901. },
  902. {
  903. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  904. "UpstreamSubnets" : ["0.0.0.0/0"],
  905. "Targets" :
  906. {
  907. "BytesRead" : 1,
  908. "BytesWritten" : 1,
  909. "PortForwardDurationNanoseconds" : 1
  910. }
  911. }
  912. ],
  913. "SeedSpecThreshold" : 2,
  914. "SeedPeriodNanoseconds" : 2592000000000000,
  915. "SeedPeriodKeySplits": [
  916. {
  917. "Total": 2,
  918. "Threshold": 2
  919. }
  920. ]
  921. },
  922. {
  923. "Epoch" : "%s",
  924. "Regions" : [],
  925. "PropagationChannelIDs" : ["%s"],
  926. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  927. "SeedSpecs" : [
  928. {
  929. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  930. "UpstreamSubnets" : ["0.0.0.0/0"],
  931. "Targets" :
  932. {
  933. "BytesRead" : 1,
  934. "BytesWritten" : 1,
  935. "PortForwardDurationNanoseconds" : 1
  936. }
  937. }
  938. ],
  939. "SeedSpecThreshold" : 1,
  940. "SeedPeriodNanoseconds" : 2592000000000000,
  941. "SeedPeriodKeySplits": [
  942. {
  943. "Total": 1,
  944. "Threshold": 1
  945. }
  946. ]
  947. }
  948. ]
  949. }
  950. `
  951. propagationChannelID, _ := common.MakeSecureRandomStringHex(8)
  952. now := time.Now().UTC()
  953. epoch := now.Truncate(720 * time.Hour)
  954. epochStr := epoch.Format(time.RFC3339Nano)
  955. oslConfigJSON := fmt.Sprintf(
  956. oslConfigJSONFormat,
  957. epochStr, propagationChannelID,
  958. epochStr, propagationChannelID)
  959. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  960. if err != nil {
  961. t.Fatalf("error paving osl config file: %s", err)
  962. }
  963. return propagationChannelID
  964. }
  965. func paveTacticsConfigFile(
  966. t *testing.T, tacticsConfigFilename string,
  967. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  968. tunnelProtocol string,
  969. propagationChannelID string) {
  970. // Setting LimitTunnelProtocols passively exercises the
  971. // server-side LimitTunnelProtocols enforcement.
  972. tacticsConfigJSONFormat := `
  973. {
  974. "RequestPublicKey" : "%s",
  975. "RequestPrivateKey" : "%s",
  976. "RequestObfuscatedKey" : "%s",
  977. "EnforceServerSide" : true,
  978. "DefaultTactics" : {
  979. "TTL" : "60s",
  980. "Probability" : 1.0,
  981. "Parameters" : {
  982. "LimitTunnelProtocols" : ["%s"]
  983. }
  984. },
  985. "FilteredTactics" : [
  986. {
  987. "Filter" : {
  988. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  989. "SpeedTestRTTMilliseconds" : {
  990. "Aggregation" : "Median",
  991. "AtLeast" : 1
  992. }
  993. },
  994. "Tactics" : {
  995. "Parameters" : {
  996. "TunnelConnectTimeout" : "20s",
  997. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000}
  998. }
  999. }
  1000. }
  1001. ]
  1002. }
  1003. `
  1004. tacticsConfigJSON := fmt.Sprintf(
  1005. tacticsConfigJSONFormat,
  1006. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1007. tunnelProtocol,
  1008. propagationChannelID)
  1009. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1010. if err != nil {
  1011. t.Fatalf("error paving tactics config file: %s", err)
  1012. }
  1013. }
  1014. func sendNotificationReceived(c chan<- struct{}) {
  1015. select {
  1016. case c <- *new(struct{}):
  1017. default:
  1018. }
  1019. }
  1020. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1021. select {
  1022. case <-c:
  1023. case <-timeoutSignal:
  1024. t.Fatalf(timeoutMessage)
  1025. }
  1026. }