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