server_test.go 33 KB

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