server_test.go 33 KB

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