server_test.go 33 KB

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