server_test.go 34 KB

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