server_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. // Note: calling LoadConfig ensures the Config is fully initialized
  469. clientConfigJSON := fmt.Sprintf(`
  470. {
  471. "ClientPlatform" : "Windows",
  472. "ClientVersion" : "0",
  473. "SponsorId" : "0",
  474. "PropagationChannelId" : "0",
  475. "DisableRemoteServerListFetcher" : true,
  476. "UseIndistinguishableTLS" : true,
  477. "EstablishTunnelPausePeriodSeconds" : 1,
  478. "ConnectionWorkerPoolSize" : %d,
  479. "TunnelProtocols" : ["%s"]
  480. }`, numTunnels, runConfig.tunnelProtocol)
  481. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  482. clientConfig.DataStoreDirectory = testDataDirName
  483. err = psiphon.InitDataStore(clientConfig)
  484. if err != nil {
  485. t.Fatalf("error initializing client datastore: %s", err)
  486. }
  487. psiphon.DeleteSLOKs()
  488. if !runConfig.doDefaultSponsorID {
  489. clientConfig.SponsorId = sponsorID
  490. }
  491. clientConfig.PropagationChannelId = propagationChannelID
  492. clientConfig.TunnelPoolSize = numTunnels
  493. clientConfig.TargetServerEntry = string(encodedServerEntry)
  494. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  495. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  496. clientConfig.EmitSLOKs = true
  497. if runConfig.doClientVerification {
  498. clientConfig.ClientPlatform = "Android"
  499. }
  500. if !runConfig.omitAuthorization {
  501. clientConfig.Authorizations = []string{clientAuthorization}
  502. }
  503. if doTactics {
  504. // Use a distinct prefix for network ID for each test run to
  505. // ensure tactics from different runs don't apply; this is
  506. // a workaround for the singleton datastore.
  507. prefix := time.Now().String()
  508. clientConfig.NetworkIDGetter = &testNetworkGetter{prefix: prefix}
  509. }
  510. if doTactics {
  511. // Configure nonfunctional values that must be overridden by tactics.
  512. applyParameters := make(map[string]interface{})
  513. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  514. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  515. err = clientConfig.SetClientParameters("", true, applyParameters)
  516. if err != nil {
  517. t.Fatalf("SetClientParameters failed: %s", err)
  518. }
  519. }
  520. controller, err := psiphon.NewController(clientConfig)
  521. if err != nil {
  522. t.Fatalf("error creating client controller: %s", err)
  523. }
  524. tunnelsEstablished := make(chan struct{}, 1)
  525. homepageReceived := make(chan struct{}, 1)
  526. slokSeeded := make(chan struct{}, 1)
  527. verificationRequired := make(chan struct{}, 1)
  528. verificationCompleted := make(chan struct{}, 1)
  529. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  530. func(notice []byte) {
  531. //fmt.Printf("%s\n", string(notice))
  532. noticeType, payload, err := psiphon.GetNotice(notice)
  533. if err != nil {
  534. return
  535. }
  536. switch noticeType {
  537. case "Tunnels":
  538. // Do not set verification payload until tunnel is
  539. // established. Otherwise will silently take no action.
  540. controller.SetClientVerificationPayloadForActiveTunnels("")
  541. count := int(payload["count"].(float64))
  542. if count >= numTunnels {
  543. sendNotificationReceived(tunnelsEstablished)
  544. }
  545. case "Homepage":
  546. homepageURL := payload["url"].(string)
  547. if homepageURL != expectedHomepageURL {
  548. // TODO: wrong goroutine for t.FatalNow()
  549. t.Fatalf("unexpected homepage: %s", homepageURL)
  550. }
  551. sendNotificationReceived(homepageReceived)
  552. case "SLOKSeeded":
  553. sendNotificationReceived(slokSeeded)
  554. case "ClientVerificationRequired":
  555. sendNotificationReceived(verificationRequired)
  556. controller.SetClientVerificationPayloadForActiveTunnels(dummyClientVerificationPayload)
  557. case "NoticeClientVerificationRequestCompleted":
  558. sendNotificationReceived(verificationCompleted)
  559. }
  560. }))
  561. ctx, cancelFunc := context.WithCancel(context.Background())
  562. controllerWaitGroup := new(sync.WaitGroup)
  563. controllerWaitGroup.Add(1)
  564. go func() {
  565. defer controllerWaitGroup.Done()
  566. controller.Run(ctx)
  567. }()
  568. defer func() {
  569. cancelFunc()
  570. shutdownTimeout := time.NewTimer(20 * time.Second)
  571. shutdownOk := make(chan struct{}, 1)
  572. go func() {
  573. controllerWaitGroup.Wait()
  574. shutdownOk <- *new(struct{})
  575. }()
  576. select {
  577. case <-shutdownOk:
  578. case <-shutdownTimeout.C:
  579. t.Fatalf("controller shutdown timeout exceeded")
  580. }
  581. }()
  582. // Test: tunnels must be established, and correct homepage
  583. // must be received, within 30 seconds
  584. timeoutSignal := make(chan struct{})
  585. go func() {
  586. timer := time.NewTimer(30 * time.Second)
  587. <-timer.C
  588. close(timeoutSignal)
  589. }()
  590. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  591. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  592. if runConfig.doClientVerification {
  593. waitOnNotification(t, verificationRequired, timeoutSignal, "verification required timeout exceeded")
  594. waitOnNotification(t, verificationCompleted, timeoutSignal, "verification completed timeout exceeded")
  595. }
  596. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  597. if runConfig.doTunneledWebRequest {
  598. // Test: tunneled web site fetch
  599. err = makeTunneledWebRequest(
  600. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  601. if err == nil {
  602. if expectTrafficFailure {
  603. t.Fatalf("unexpected tunneled web request success")
  604. }
  605. } else {
  606. if !expectTrafficFailure {
  607. t.Fatalf("tunneled web request failed: %s", err)
  608. }
  609. }
  610. }
  611. if runConfig.doTunneledNTPRequest {
  612. // Test: tunneled UDP packets
  613. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  614. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  615. if err == nil {
  616. if expectTrafficFailure {
  617. t.Fatalf("unexpected tunneled NTP request success")
  618. }
  619. } else {
  620. if !expectTrafficFailure {
  621. t.Fatalf("tunneled NTP request failed: %s", err)
  622. }
  623. }
  624. }
  625. // Test: await SLOK payload
  626. if !expectTrafficFailure {
  627. time.Sleep(1 * time.Second)
  628. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  629. numSLOKs := psiphon.CountSLOKs()
  630. if numSLOKs != expectedNumSLOKs {
  631. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  632. }
  633. }
  634. }
  635. func makeTunneledWebRequest(
  636. t *testing.T,
  637. localHTTPProxyPort int,
  638. requestURL, expectedResponseBody string) error {
  639. roundTripTimeout := 30 * time.Second
  640. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  641. if err != nil {
  642. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  643. }
  644. httpClient := &http.Client{
  645. Transport: &http.Transport{
  646. Proxy: http.ProxyURL(proxyUrl),
  647. },
  648. Timeout: roundTripTimeout,
  649. }
  650. response, err := httpClient.Get(requestURL)
  651. if err != nil {
  652. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  653. }
  654. body, err := ioutil.ReadAll(response.Body)
  655. if err != nil {
  656. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  657. }
  658. response.Body.Close()
  659. if string(body) != expectedResponseBody {
  660. return fmt.Errorf("unexpected proxied HTTP response")
  661. }
  662. return nil
  663. }
  664. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  665. timeout := 20 * time.Second
  666. var err error
  667. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  668. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  669. if err == nil {
  670. break
  671. }
  672. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  673. }
  674. return err
  675. }
  676. var nextUDPProxyPort = 7300
  677. func makeTunneledNTPRequestAttempt(
  678. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  679. nextUDPProxyPort++
  680. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  681. if err != nil {
  682. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  683. }
  684. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  685. // handles it, and then terminates.
  686. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  687. if waitGroup != nil {
  688. defer waitGroup.Done()
  689. }
  690. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  691. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  692. if err != nil {
  693. t.Logf("ListenUDP for %s failed: %s", destination, err)
  694. return
  695. }
  696. defer serverUDPConn.Close()
  697. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  698. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  699. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  700. buffer[udpgwPreambleSize:])
  701. if err != nil {
  702. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  703. return
  704. }
  705. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  706. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  707. if err != nil {
  708. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  709. return
  710. }
  711. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  712. if err != nil {
  713. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  714. return
  715. }
  716. defer socksTCPConn.Close()
  717. flags := uint8(0)
  718. if destinationPort == 53 {
  719. flags = udpgwProtocolFlagDNS
  720. }
  721. err = writeUdpgwPreamble(
  722. udpgwPreambleSize,
  723. flags,
  724. 0,
  725. destinationIP,
  726. destinationPort,
  727. uint16(packetSize),
  728. buffer)
  729. if err != nil {
  730. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  731. return
  732. }
  733. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  734. if err != nil {
  735. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  736. return
  737. }
  738. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  739. if err != nil {
  740. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  741. return
  742. }
  743. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  744. if err != nil {
  745. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  746. return
  747. }
  748. }
  749. // Tunneled DNS request
  750. waitGroup := new(sync.WaitGroup)
  751. waitGroup.Add(1)
  752. go localUDPProxy(
  753. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  754. 53,
  755. waitGroup)
  756. // TODO: properly synchronize with local UDP proxy startup
  757. time.Sleep(1 * time.Second)
  758. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  759. if err != nil {
  760. return fmt.Errorf("DialUDP failed: %s", err)
  761. }
  762. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  763. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  764. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  765. clientUDPConn.Close()
  766. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  767. err = errors.New("no address")
  768. }
  769. if err != nil {
  770. return fmt.Errorf("ResolveIP failed: %s", err)
  771. }
  772. waitGroup.Wait()
  773. // Tunneled NTP request
  774. waitGroup = new(sync.WaitGroup)
  775. waitGroup.Add(1)
  776. go localUDPProxy(
  777. addrs[0][len(addrs[0])-4:],
  778. 123,
  779. waitGroup)
  780. // TODO: properly synchronize with local UDP proxy startup
  781. time.Sleep(1 * time.Second)
  782. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  783. if err != nil {
  784. return fmt.Errorf("DialUDP failed: %s", err)
  785. }
  786. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  787. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  788. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  789. ntpData := make([]byte, 48)
  790. ntpData[0] = 3<<3 | 3
  791. _, err = clientUDPConn.Write(ntpData)
  792. if err != nil {
  793. clientUDPConn.Close()
  794. return fmt.Errorf("NTP Write failed: %s", err)
  795. }
  796. _, err = clientUDPConn.Read(ntpData)
  797. if err != nil {
  798. clientUDPConn.Close()
  799. return fmt.Errorf("NTP Read failed: %s", err)
  800. }
  801. clientUDPConn.Close()
  802. var sec, frac uint64
  803. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  804. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  805. nsec := sec * 1e9
  806. nsec += (frac * 1e9) >> 32
  807. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  808. now := time.Now()
  809. diff := ntpNow.Sub(now)
  810. if diff < 0 {
  811. diff = -diff
  812. }
  813. if diff > 1*time.Minute {
  814. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  815. }
  816. waitGroup.Wait()
  817. return nil
  818. }
  819. func pavePsinetDatabaseFile(
  820. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  821. sponsorID, _ := common.MakeRandomStringHex(8)
  822. fakeDomain, _ := common.MakeRandomStringHex(4)
  823. fakePath, _ := common.MakeRandomStringHex(4)
  824. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  825. psinetJSONFormat := `
  826. {
  827. "default_sponsor_id" : "%s",
  828. "sponsors": {
  829. "%s": {
  830. "home_pages": {
  831. "None": [
  832. {
  833. "region": null,
  834. "url": "%s"
  835. }
  836. ]
  837. }
  838. }
  839. }
  840. }
  841. `
  842. defaultSponsorID := ""
  843. if useDefaultSponsorID {
  844. defaultSponsorID = sponsorID
  845. }
  846. psinetJSON := fmt.Sprintf(
  847. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  848. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  849. if err != nil {
  850. t.Fatalf("error paving psinet database file: %s", err)
  851. }
  852. return sponsorID, expectedHomepageURL
  853. }
  854. func paveTrafficRulesFile(
  855. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  856. requireAuthorization, deny bool) {
  857. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  858. allowUDPPorts := "53, 123"
  859. if deny {
  860. allowTCPPorts = "0"
  861. allowUDPPorts = "0"
  862. }
  863. authorizationFilterFormat := `,
  864. "AuthorizedAccessTypes" : ["%s"]
  865. `
  866. authorizationFilter := ""
  867. if requireAuthorization {
  868. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  869. }
  870. trafficRulesJSONFormat := `
  871. {
  872. "DefaultRules" : {
  873. "RateLimits" : {
  874. "ReadBytesPerSecond": 16384,
  875. "WriteBytesPerSecond": 16384
  876. },
  877. "AllowTCPPorts" : [0],
  878. "AllowUDPPorts" : [0]
  879. },
  880. "FilteredRules" : [
  881. {
  882. "Filter" : {
  883. "HandshakeParameters" : {
  884. "propagation_channel_id" : ["%s"]
  885. }%s
  886. },
  887. "Rules" : {
  888. "RateLimits" : {
  889. "ReadUnthrottledBytes": 132352,
  890. "WriteUnthrottledBytes": 132352
  891. },
  892. "AllowTCPPorts" : [%s],
  893. "AllowUDPPorts" : [%s]
  894. }
  895. }
  896. ]
  897. }
  898. `
  899. trafficRulesJSON := fmt.Sprintf(
  900. trafficRulesJSONFormat, propagationChannelID, authorizationFilter, allowTCPPorts, allowUDPPorts)
  901. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  902. if err != nil {
  903. t.Fatalf("error paving traffic rules file: %s", err)
  904. }
  905. }
  906. var expectedNumSLOKs = 3
  907. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  908. oslConfigJSONFormat := `
  909. {
  910. "Schemes" : [
  911. {
  912. "Epoch" : "%s",
  913. "Regions" : [],
  914. "PropagationChannelIDs" : ["%s"],
  915. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  916. "SeedSpecs" : [
  917. {
  918. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  919. "UpstreamSubnets" : ["0.0.0.0/0"],
  920. "Targets" :
  921. {
  922. "BytesRead" : 1,
  923. "BytesWritten" : 1,
  924. "PortForwardDurationNanoseconds" : 1
  925. }
  926. },
  927. {
  928. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  929. "UpstreamSubnets" : ["0.0.0.0/0"],
  930. "Targets" :
  931. {
  932. "BytesRead" : 1,
  933. "BytesWritten" : 1,
  934. "PortForwardDurationNanoseconds" : 1
  935. }
  936. }
  937. ],
  938. "SeedSpecThreshold" : 2,
  939. "SeedPeriodNanoseconds" : 2592000000000000,
  940. "SeedPeriodKeySplits": [
  941. {
  942. "Total": 2,
  943. "Threshold": 2
  944. }
  945. ]
  946. },
  947. {
  948. "Epoch" : "%s",
  949. "Regions" : [],
  950. "PropagationChannelIDs" : ["%s"],
  951. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  952. "SeedSpecs" : [
  953. {
  954. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  955. "UpstreamSubnets" : ["0.0.0.0/0"],
  956. "Targets" :
  957. {
  958. "BytesRead" : 1,
  959. "BytesWritten" : 1,
  960. "PortForwardDurationNanoseconds" : 1
  961. }
  962. }
  963. ],
  964. "SeedSpecThreshold" : 1,
  965. "SeedPeriodNanoseconds" : 2592000000000000,
  966. "SeedPeriodKeySplits": [
  967. {
  968. "Total": 1,
  969. "Threshold": 1
  970. }
  971. ]
  972. }
  973. ]
  974. }
  975. `
  976. propagationChannelID, _ := common.MakeRandomStringHex(8)
  977. now := time.Now().UTC()
  978. epoch := now.Truncate(720 * time.Hour)
  979. epochStr := epoch.Format(time.RFC3339Nano)
  980. oslConfigJSON := fmt.Sprintf(
  981. oslConfigJSONFormat,
  982. epochStr, propagationChannelID,
  983. epochStr, propagationChannelID)
  984. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  985. if err != nil {
  986. t.Fatalf("error paving osl config file: %s", err)
  987. }
  988. return propagationChannelID
  989. }
  990. func paveTacticsConfigFile(
  991. t *testing.T, tacticsConfigFilename string,
  992. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  993. tunnelProtocol string,
  994. propagationChannelID string) {
  995. // Setting LimitTunnelProtocols passively exercises the
  996. // server-side LimitTunnelProtocols enforcement.
  997. tacticsConfigJSONFormat := `
  998. {
  999. "RequestPublicKey" : "%s",
  1000. "RequestPrivateKey" : "%s",
  1001. "RequestObfuscatedKey" : "%s",
  1002. "EnforceServerSide" : true,
  1003. "DefaultTactics" : {
  1004. "TTL" : "60s",
  1005. "Probability" : 1.0,
  1006. "Parameters" : {
  1007. "LimitTunnelProtocols" : ["%s"]
  1008. }
  1009. },
  1010. "FilteredTactics" : [
  1011. {
  1012. "Filter" : {
  1013. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1014. "SpeedTestRTTMilliseconds" : {
  1015. "Aggregation" : "Median",
  1016. "AtLeast" : 1
  1017. }
  1018. },
  1019. "Tactics" : {
  1020. "Parameters" : {
  1021. "TunnelConnectTimeout" : "20s",
  1022. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000}
  1023. }
  1024. }
  1025. }
  1026. ]
  1027. }
  1028. `
  1029. tacticsConfigJSON := fmt.Sprintf(
  1030. tacticsConfigJSONFormat,
  1031. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1032. tunnelProtocol,
  1033. propagationChannelID)
  1034. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1035. if err != nil {
  1036. t.Fatalf("error paving tactics config file: %s", err)
  1037. }
  1038. }
  1039. func sendNotificationReceived(c chan<- struct{}) {
  1040. select {
  1041. case c <- *new(struct{}):
  1042. default:
  1043. }
  1044. }
  1045. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1046. select {
  1047. case <-c:
  1048. case <-timeoutSignal:
  1049. t.Fatalf(timeoutMessage)
  1050. }
  1051. }
  1052. const dummyClientVerificationPayload = `
  1053. {
  1054. "status": 0,
  1055. "payload": ""
  1056. }`
  1057. type testNetworkGetter struct {
  1058. prefix string
  1059. }
  1060. func (t *testNetworkGetter) GetNetworkID() string {
  1061. return t.prefix + "NETWORK1"
  1062. }