server_test.go 33 KB

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