server_test.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. "golang.org/x/net/proxy"
  40. )
  41. var serverIPAddress, testDataDirName string
  42. var mockWebServerURL, mockWebServerExpectedResponse string
  43. var mockWebServerPort = 8080
  44. func TestMain(m *testing.M) {
  45. flag.Parse()
  46. var err error
  47. for _, interfaceName := range []string{"eth0", "en0"} {
  48. var serverIPv4Address, serverIPv6Address net.IP
  49. serverIPv4Address, serverIPv6Address, err = common.GetInterfaceIPAddresses(interfaceName)
  50. if err == nil {
  51. if serverIPv4Address != nil {
  52. serverIPAddress = serverIPv4Address.String()
  53. } else {
  54. serverIPAddress = serverIPv6Address.String()
  55. }
  56. break
  57. }
  58. }
  59. if err != nil {
  60. fmt.Printf("error getting server IP address: %s", err)
  61. os.Exit(1)
  62. }
  63. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  64. if err != nil {
  65. fmt.Printf("TempDir failed: %s\n", err)
  66. os.Exit(1)
  67. }
  68. defer os.RemoveAll(testDataDirName)
  69. os.Remove(filepath.Join(testDataDirName, psiphon.DATA_STORE_FILENAME))
  70. psiphon.SetEmitDiagnosticNotices(true)
  71. CLIENT_VERIFICATION_REQUIRED = true
  72. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  73. os.Exit(m.Run())
  74. }
  75. func runMockWebServer() (string, string) {
  76. responseBody, _ := common.MakeRandomStringHex(100000)
  77. serveMux := http.NewServeMux()
  78. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  79. w.Write([]byte(responseBody))
  80. })
  81. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  82. server := &http.Server{
  83. Addr: webServerAddress,
  84. Handler: serveMux,
  85. }
  86. go func() {
  87. err := server.ListenAndServe()
  88. if err != nil {
  89. fmt.Printf("error running mock web server: %s\n", err)
  90. os.Exit(1)
  91. }
  92. }()
  93. // TODO: properly synchronize with web server readiness
  94. time.Sleep(1 * time.Second)
  95. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  96. }
  97. // Note: not testing fronting meek protocols, which client is
  98. // hard-wired to except running on privileged ports 80 and 443.
  99. func TestSSH(t *testing.T) {
  100. runServer(t,
  101. &runServerConfig{
  102. tunnelProtocol: "SSH",
  103. enableSSHAPIRequests: true,
  104. doHotReload: false,
  105. doDefaultSessionID: false,
  106. denyTrafficRules: false,
  107. doClientVerification: true,
  108. doTunneledWebRequest: true,
  109. doTunneledNTPRequest: true,
  110. })
  111. }
  112. func TestOSSH(t *testing.T) {
  113. runServer(t,
  114. &runServerConfig{
  115. tunnelProtocol: "OSSH",
  116. enableSSHAPIRequests: true,
  117. doHotReload: false,
  118. doDefaultSessionID: false,
  119. denyTrafficRules: false,
  120. doClientVerification: false,
  121. doTunneledWebRequest: true,
  122. doTunneledNTPRequest: true,
  123. })
  124. }
  125. func TestUnfrontedMeek(t *testing.T) {
  126. runServer(t,
  127. &runServerConfig{
  128. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  129. enableSSHAPIRequests: true,
  130. doHotReload: false,
  131. doDefaultSessionID: false,
  132. denyTrafficRules: false,
  133. doClientVerification: false,
  134. doTunneledWebRequest: true,
  135. doTunneledNTPRequest: true,
  136. })
  137. }
  138. func TestUnfrontedMeekHTTPS(t *testing.T) {
  139. runServer(t,
  140. &runServerConfig{
  141. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  142. enableSSHAPIRequests: true,
  143. doHotReload: false,
  144. doDefaultSessionID: false,
  145. denyTrafficRules: false,
  146. doClientVerification: false,
  147. doTunneledWebRequest: true,
  148. doTunneledNTPRequest: true,
  149. })
  150. }
  151. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  152. runServer(t,
  153. &runServerConfig{
  154. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  155. enableSSHAPIRequests: true,
  156. doHotReload: false,
  157. doDefaultSessionID: false,
  158. denyTrafficRules: false,
  159. doClientVerification: false,
  160. doTunneledWebRequest: true,
  161. doTunneledNTPRequest: true,
  162. })
  163. }
  164. func TestWebTransportAPIRequests(t *testing.T) {
  165. runServer(t,
  166. &runServerConfig{
  167. tunnelProtocol: "OSSH",
  168. enableSSHAPIRequests: false,
  169. doHotReload: false,
  170. doDefaultSessionID: false,
  171. denyTrafficRules: false,
  172. doClientVerification: true,
  173. doTunneledWebRequest: true,
  174. doTunneledNTPRequest: true,
  175. })
  176. }
  177. func TestHotReload(t *testing.T) {
  178. runServer(t,
  179. &runServerConfig{
  180. tunnelProtocol: "OSSH",
  181. enableSSHAPIRequests: true,
  182. doHotReload: true,
  183. doDefaultSessionID: false,
  184. denyTrafficRules: false,
  185. doClientVerification: false,
  186. doTunneledWebRequest: true,
  187. doTunneledNTPRequest: true,
  188. })
  189. }
  190. func TestDefaultSessionID(t *testing.T) {
  191. runServer(t,
  192. &runServerConfig{
  193. tunnelProtocol: "OSSH",
  194. enableSSHAPIRequests: true,
  195. doHotReload: true,
  196. doDefaultSessionID: true,
  197. denyTrafficRules: false,
  198. doClientVerification: false,
  199. doTunneledWebRequest: true,
  200. doTunneledNTPRequest: true,
  201. })
  202. }
  203. func TestDenyTrafficRules(t *testing.T) {
  204. runServer(t,
  205. &runServerConfig{
  206. tunnelProtocol: "OSSH",
  207. enableSSHAPIRequests: true,
  208. doHotReload: true,
  209. doDefaultSessionID: false,
  210. denyTrafficRules: true,
  211. doClientVerification: false,
  212. doTunneledWebRequest: true,
  213. doTunneledNTPRequest: true,
  214. })
  215. }
  216. func TestTCPOnlySLOK(t *testing.T) {
  217. runServer(t,
  218. &runServerConfig{
  219. tunnelProtocol: "OSSH",
  220. enableSSHAPIRequests: true,
  221. doHotReload: false,
  222. doDefaultSessionID: false,
  223. denyTrafficRules: false,
  224. doClientVerification: false,
  225. doTunneledWebRequest: true,
  226. doTunneledNTPRequest: false,
  227. })
  228. }
  229. func TestUDPOnlySLOK(t *testing.T) {
  230. runServer(t,
  231. &runServerConfig{
  232. tunnelProtocol: "OSSH",
  233. enableSSHAPIRequests: true,
  234. doHotReload: false,
  235. doDefaultSessionID: false,
  236. denyTrafficRules: false,
  237. doClientVerification: false,
  238. doTunneledWebRequest: false,
  239. doTunneledNTPRequest: true,
  240. })
  241. }
  242. type runServerConfig struct {
  243. tunnelProtocol string
  244. enableSSHAPIRequests bool
  245. doHotReload bool
  246. doDefaultSessionID bool
  247. denyTrafficRules bool
  248. doClientVerification bool
  249. doTunneledWebRequest bool
  250. doTunneledNTPRequest bool
  251. }
  252. func sendNotificationReceived(c chan<- struct{}) {
  253. select {
  254. case c <- *new(struct{}):
  255. default:
  256. }
  257. }
  258. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  259. select {
  260. case <-c:
  261. case <-timeoutSignal:
  262. t.Fatalf(timeoutMessage)
  263. }
  264. }
  265. const dummyClientVerificationPayload = `
  266. {
  267. "status": 0,
  268. "payload": ""
  269. }`
  270. func runServer(t *testing.T, runConfig *runServerConfig) {
  271. // create a server
  272. serverConfigJSON, _, encodedServerEntry, err := GenerateConfig(
  273. &GenerateConfigParams{
  274. ServerIPAddress: serverIPAddress,
  275. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  276. WebServerPort: 8000,
  277. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  278. })
  279. if err != nil {
  280. t.Fatalf("error generating server config: %s", err)
  281. }
  282. // customize server config
  283. // Pave psinet with random values to test handshake homepages.
  284. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  285. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  286. t, runConfig.doDefaultSessionID, psinetFilename)
  287. // Pave OSL config for SLOK testing
  288. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  289. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  290. // Pave traffic rules file which exercises handshake parameter filtering. Client
  291. // must handshake with specified sponsor ID in order to allow ports for tunneled
  292. // requests.
  293. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  294. paveTrafficRulesFile(t, trafficRulesFilename, propagationChannelID, runConfig.denyTrafficRules)
  295. var serverConfig map[string]interface{}
  296. json.Unmarshal(serverConfigJSON, &serverConfig)
  297. serverConfig["GeoIPDatabaseFilename"] = ""
  298. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  299. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  300. serverConfig["OSLConfigFilename"] = oslConfigFilename
  301. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  302. serverConfig["LogLevel"] = "debug"
  303. serverConfigJSON, _ = json.Marshal(serverConfig)
  304. // run server
  305. serverWaitGroup := new(sync.WaitGroup)
  306. serverWaitGroup.Add(1)
  307. go func() {
  308. defer serverWaitGroup.Done()
  309. err := RunServices(serverConfigJSON)
  310. if err != nil {
  311. // TODO: wrong goroutine for t.FatalNow()
  312. t.Fatalf("error running server: %s", err)
  313. }
  314. }()
  315. defer func() {
  316. // Test: orderly server shutdown
  317. p, _ := os.FindProcess(os.Getpid())
  318. p.Signal(os.Interrupt)
  319. shutdownTimeout := time.NewTimer(5 * time.Second)
  320. shutdownOk := make(chan struct{}, 1)
  321. go func() {
  322. serverWaitGroup.Wait()
  323. shutdownOk <- *new(struct{})
  324. }()
  325. select {
  326. case <-shutdownOk:
  327. case <-shutdownTimeout.C:
  328. t.Fatalf("server shutdown timeout exceeded")
  329. }
  330. }()
  331. // TODO: monitor logs for more robust wait-until-loaded
  332. time.Sleep(1 * time.Second)
  333. // Test: hot reload (of psinet and traffic rules)
  334. if runConfig.doHotReload {
  335. // Pave new config files with different random values.
  336. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  337. t, runConfig.doDefaultSessionID, psinetFilename)
  338. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  339. paveTrafficRulesFile(
  340. t, trafficRulesFilename, propagationChannelID, runConfig.denyTrafficRules)
  341. p, _ := os.FindProcess(os.Getpid())
  342. p.Signal(syscall.SIGUSR1)
  343. // TODO: monitor logs for more robust wait-until-reloaded
  344. time.Sleep(1 * time.Second)
  345. // After reloading psinet, the new sponsorID/expectedHomepageURL
  346. // should be active, as tested in the client "Homepage" notice
  347. // handler below.
  348. }
  349. // Exercise server_load logging
  350. p, _ := os.FindProcess(os.Getpid())
  351. p.Signal(syscall.SIGUSR2)
  352. // connect to server with client
  353. // TODO: currently, TargetServerEntry only works with one tunnel
  354. numTunnels := 1
  355. localSOCKSProxyPort := 1081
  356. localHTTPProxyPort := 8081
  357. establishTunnelPausePeriodSeconds := 1
  358. // Note: calling LoadConfig ensures all *int config fields are initialized
  359. clientConfigJSON := `
  360. {
  361. "ClientPlatform" : "Windows",
  362. "ClientVersion" : "0",
  363. "SponsorId" : "0",
  364. "PropagationChannelId" : "0",
  365. "DisableRemoteServerListFetcher" : true,
  366. "UseIndistinguishableTLS" : true
  367. }`
  368. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  369. if !runConfig.doDefaultSessionID {
  370. clientConfig.SponsorId = sponsorID
  371. }
  372. clientConfig.PropagationChannelId = propagationChannelID
  373. clientConfig.ConnectionWorkerPoolSize = numTunnels
  374. clientConfig.TunnelPoolSize = numTunnels
  375. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  376. clientConfig.TargetServerEntry = string(encodedServerEntry)
  377. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  378. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  379. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  380. clientConfig.EmitSLOKs = true
  381. if runConfig.doClientVerification {
  382. clientConfig.ClientPlatform = "Android"
  383. }
  384. clientConfig.DataStoreDirectory = testDataDirName
  385. err = psiphon.InitDataStore(clientConfig)
  386. if err != nil {
  387. t.Fatalf("error initializing client datastore: %s", err)
  388. }
  389. psiphon.DeleteSLOKs()
  390. controller, err := psiphon.NewController(clientConfig)
  391. if err != nil {
  392. t.Fatalf("error creating client controller: %s", err)
  393. }
  394. tunnelsEstablished := make(chan struct{}, 1)
  395. homepageReceived := make(chan struct{}, 1)
  396. slokSeeded := make(chan struct{}, 1)
  397. verificationRequired := make(chan struct{}, 1)
  398. verificationCompleted := make(chan struct{}, 1)
  399. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  400. func(notice []byte) {
  401. //fmt.Printf("%s\n", string(notice))
  402. noticeType, payload, err := psiphon.GetNotice(notice)
  403. if err != nil {
  404. return
  405. }
  406. switch noticeType {
  407. case "Tunnels":
  408. // Do not set verification payload until tunnel is
  409. // established. Otherwise will silently take no action.
  410. controller.SetClientVerificationPayloadForActiveTunnels("")
  411. count := int(payload["count"].(float64))
  412. if count >= numTunnels {
  413. sendNotificationReceived(tunnelsEstablished)
  414. }
  415. case "Homepage":
  416. homepageURL := payload["url"].(string)
  417. if homepageURL != expectedHomepageURL {
  418. // TODO: wrong goroutine for t.FatalNow()
  419. t.Fatalf("unexpected homepage: %s", homepageURL)
  420. }
  421. sendNotificationReceived(homepageReceived)
  422. case "SLOKSeeded":
  423. sendNotificationReceived(slokSeeded)
  424. case "ClientVerificationRequired":
  425. sendNotificationReceived(verificationRequired)
  426. controller.SetClientVerificationPayloadForActiveTunnels(dummyClientVerificationPayload)
  427. case "NoticeClientVerificationRequestCompleted":
  428. sendNotificationReceived(verificationCompleted)
  429. }
  430. }))
  431. ctx, cancelFunc := context.WithCancel(context.Background())
  432. controllerWaitGroup := new(sync.WaitGroup)
  433. controllerWaitGroup.Add(1)
  434. go func() {
  435. defer controllerWaitGroup.Done()
  436. controller.Run(ctx)
  437. }()
  438. defer func() {
  439. cancelFunc()
  440. shutdownTimeout := time.NewTimer(20 * time.Second)
  441. shutdownOk := make(chan struct{}, 1)
  442. go func() {
  443. controllerWaitGroup.Wait()
  444. shutdownOk <- *new(struct{})
  445. }()
  446. select {
  447. case <-shutdownOk:
  448. case <-shutdownTimeout.C:
  449. t.Fatalf("controller shutdown timeout exceeded")
  450. }
  451. }()
  452. // Test: tunnels must be established, and correct homepage
  453. // must be received, within 30 seconds
  454. timeoutSignal := make(chan struct{})
  455. go func() {
  456. timer := time.NewTimer(30 * time.Second)
  457. <-timer.C
  458. close(timeoutSignal)
  459. }()
  460. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  461. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  462. if runConfig.doClientVerification {
  463. waitOnNotification(t, verificationRequired, timeoutSignal, "verification required timeout exceeded")
  464. waitOnNotification(t, verificationCompleted, timeoutSignal, "verification completed timeout exceeded")
  465. }
  466. if runConfig.doTunneledWebRequest {
  467. // Test: tunneled web site fetch
  468. err = makeTunneledWebRequest(
  469. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  470. if err == nil {
  471. if runConfig.denyTrafficRules {
  472. t.Fatalf("unexpected tunneled web request success")
  473. }
  474. } else {
  475. if !runConfig.denyTrafficRules {
  476. t.Fatalf("tunneled web request failed: %s", err)
  477. }
  478. }
  479. }
  480. if runConfig.doTunneledNTPRequest {
  481. // Test: tunneled UDP packets
  482. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  483. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  484. if err == nil {
  485. if runConfig.denyTrafficRules {
  486. t.Fatalf("unexpected tunneled NTP request success")
  487. }
  488. } else {
  489. if !runConfig.denyTrafficRules {
  490. t.Fatalf("tunneled NTP request failed: %s", err)
  491. }
  492. }
  493. }
  494. // Test: await SLOK payload
  495. if !runConfig.denyTrafficRules {
  496. time.Sleep(1 * time.Second)
  497. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  498. numSLOKs := psiphon.CountSLOKs()
  499. if numSLOKs != expectedNumSLOKs {
  500. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  501. }
  502. }
  503. }
  504. func makeTunneledWebRequest(
  505. t *testing.T,
  506. localHTTPProxyPort int,
  507. requestURL, expectedResponseBody string) error {
  508. roundTripTimeout := 30 * time.Second
  509. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  510. if err != nil {
  511. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  512. }
  513. httpClient := &http.Client{
  514. Transport: &http.Transport{
  515. Proxy: http.ProxyURL(proxyUrl),
  516. },
  517. Timeout: roundTripTimeout,
  518. }
  519. response, err := httpClient.Get(requestURL)
  520. if err != nil {
  521. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  522. }
  523. body, err := ioutil.ReadAll(response.Body)
  524. if err != nil {
  525. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  526. }
  527. response.Body.Close()
  528. if string(body) != expectedResponseBody {
  529. return fmt.Errorf("unexpected proxied HTTP response")
  530. }
  531. return nil
  532. }
  533. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  534. timeout := 20 * time.Second
  535. var err error
  536. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  537. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  538. if err == nil {
  539. break
  540. }
  541. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  542. }
  543. return err
  544. }
  545. var nextUDPProxyPort = 7300
  546. func makeTunneledNTPRequestAttempt(
  547. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  548. nextUDPProxyPort++
  549. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  550. if err != nil {
  551. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  552. }
  553. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  554. // handles it, and then terminates.
  555. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  556. if waitGroup != nil {
  557. defer waitGroup.Done()
  558. }
  559. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  560. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  561. if err != nil {
  562. t.Logf("ListenUDP for %s failed: %s", destination, err)
  563. return
  564. }
  565. defer serverUDPConn.Close()
  566. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  567. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  568. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  569. buffer[udpgwPreambleSize:])
  570. if err != nil {
  571. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  572. return
  573. }
  574. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  575. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  576. if err != nil {
  577. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  578. return
  579. }
  580. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  581. if err != nil {
  582. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  583. return
  584. }
  585. defer socksTCPConn.Close()
  586. flags := uint8(0)
  587. if destinationPort == 53 {
  588. flags = udpgwProtocolFlagDNS
  589. }
  590. err = writeUdpgwPreamble(
  591. udpgwPreambleSize,
  592. flags,
  593. 0,
  594. destinationIP,
  595. destinationPort,
  596. uint16(packetSize),
  597. buffer)
  598. if err != nil {
  599. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  600. return
  601. }
  602. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  603. if err != nil {
  604. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  605. return
  606. }
  607. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  608. if err != nil {
  609. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  610. return
  611. }
  612. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  613. if err != nil {
  614. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  615. return
  616. }
  617. }
  618. // Tunneled DNS request
  619. waitGroup := new(sync.WaitGroup)
  620. waitGroup.Add(1)
  621. go localUDPProxy(
  622. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  623. 53,
  624. waitGroup)
  625. // TODO: properly synchronize with local UDP proxy startup
  626. time.Sleep(1 * time.Second)
  627. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  628. if err != nil {
  629. return fmt.Errorf("DialUDP failed: %s", err)
  630. }
  631. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  632. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  633. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  634. clientUDPConn.Close()
  635. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  636. err = errors.New("no address")
  637. }
  638. if err != nil {
  639. return fmt.Errorf("ResolveIP failed: %s", err)
  640. }
  641. waitGroup.Wait()
  642. // Tunneled NTP request
  643. waitGroup = new(sync.WaitGroup)
  644. waitGroup.Add(1)
  645. go localUDPProxy(
  646. addrs[0][len(addrs[0])-4:],
  647. 123,
  648. waitGroup)
  649. // TODO: properly synchronize with local UDP proxy startup
  650. time.Sleep(1 * time.Second)
  651. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  652. if err != nil {
  653. return fmt.Errorf("DialUDP failed: %s", err)
  654. }
  655. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  656. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  657. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  658. ntpData := make([]byte, 48)
  659. ntpData[0] = 3<<3 | 3
  660. _, err = clientUDPConn.Write(ntpData)
  661. if err != nil {
  662. clientUDPConn.Close()
  663. return fmt.Errorf("NTP Write failed: %s", err)
  664. }
  665. _, err = clientUDPConn.Read(ntpData)
  666. if err != nil {
  667. clientUDPConn.Close()
  668. return fmt.Errorf("NTP Read failed: %s", err)
  669. }
  670. clientUDPConn.Close()
  671. var sec, frac uint64
  672. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  673. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  674. nsec := sec * 1e9
  675. nsec += (frac * 1e9) >> 32
  676. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  677. now := time.Now()
  678. diff := ntpNow.Sub(now)
  679. if diff < 0 {
  680. diff = -diff
  681. }
  682. if diff > 1*time.Minute {
  683. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  684. }
  685. waitGroup.Wait()
  686. return nil
  687. }
  688. func pavePsinetDatabaseFile(
  689. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  690. sponsorID, _ := common.MakeRandomStringHex(8)
  691. fakeDomain, _ := common.MakeRandomStringHex(4)
  692. fakePath, _ := common.MakeRandomStringHex(4)
  693. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  694. psinetJSONFormat := `
  695. {
  696. "default_sponsor_id" : "%s",
  697. "sponsors": {
  698. "%s": {
  699. "home_pages": {
  700. "None": [
  701. {
  702. "region": null,
  703. "url": "%s"
  704. }
  705. ]
  706. }
  707. }
  708. }
  709. }
  710. `
  711. defaultSponsorID := ""
  712. if useDefaultSponsorID {
  713. defaultSponsorID = sponsorID
  714. }
  715. psinetJSON := fmt.Sprintf(
  716. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  717. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  718. if err != nil {
  719. t.Fatalf("error paving psinet database file: %s", err)
  720. }
  721. return sponsorID, expectedHomepageURL
  722. }
  723. func paveTrafficRulesFile(
  724. t *testing.T, trafficRulesFilename, propagationChannelID string, deny bool) {
  725. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  726. allowUDPPorts := "53, 123"
  727. if deny {
  728. allowTCPPorts = "0"
  729. allowUDPPorts = "0"
  730. }
  731. trafficRulesJSONFormat := `
  732. {
  733. "DefaultRules" : {
  734. "RateLimits" : {
  735. "ReadBytesPerSecond": 16384,
  736. "WriteBytesPerSecond": 16384
  737. },
  738. "AllowTCPPorts" : [0],
  739. "AllowUDPPorts" : [0]
  740. },
  741. "FilteredRules" : [
  742. {
  743. "Filter" : {
  744. "HandshakeParameters" : {
  745. "propagation_channel_id" : ["%s"]
  746. }
  747. },
  748. "Rules" : {
  749. "RateLimits" : {
  750. "ReadUnthrottledBytes": 132352,
  751. "WriteUnthrottledBytes": 132352
  752. },
  753. "AllowTCPPorts" : [%s],
  754. "AllowUDPPorts" : [%s]
  755. }
  756. }
  757. ]
  758. }
  759. `
  760. trafficRulesJSON := fmt.Sprintf(
  761. trafficRulesJSONFormat, propagationChannelID, allowTCPPorts, allowUDPPorts)
  762. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  763. if err != nil {
  764. t.Fatalf("error paving traffic rules file: %s", err)
  765. }
  766. }
  767. var expectedNumSLOKs = 3
  768. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  769. oslConfigJSONFormat := `
  770. {
  771. "Schemes" : [
  772. {
  773. "Epoch" : "%s",
  774. "Regions" : [],
  775. "PropagationChannelIDs" : ["%s"],
  776. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  777. "SeedSpecs" : [
  778. {
  779. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  780. "UpstreamSubnets" : ["0.0.0.0/0"],
  781. "Targets" :
  782. {
  783. "BytesRead" : 1,
  784. "BytesWritten" : 1,
  785. "PortForwardDurationNanoseconds" : 1
  786. }
  787. },
  788. {
  789. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  790. "UpstreamSubnets" : ["0.0.0.0/0"],
  791. "Targets" :
  792. {
  793. "BytesRead" : 1,
  794. "BytesWritten" : 1,
  795. "PortForwardDurationNanoseconds" : 1
  796. }
  797. }
  798. ],
  799. "SeedSpecThreshold" : 2,
  800. "SeedPeriodNanoseconds" : 2592000000000000,
  801. "SeedPeriodKeySplits": [
  802. {
  803. "Total": 2,
  804. "Threshold": 2
  805. }
  806. ]
  807. },
  808. {
  809. "Epoch" : "%s",
  810. "Regions" : [],
  811. "PropagationChannelIDs" : ["%s"],
  812. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  813. "SeedSpecs" : [
  814. {
  815. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  816. "UpstreamSubnets" : ["0.0.0.0/0"],
  817. "Targets" :
  818. {
  819. "BytesRead" : 1,
  820. "BytesWritten" : 1,
  821. "PortForwardDurationNanoseconds" : 1
  822. }
  823. }
  824. ],
  825. "SeedSpecThreshold" : 1,
  826. "SeedPeriodNanoseconds" : 2592000000000000,
  827. "SeedPeriodKeySplits": [
  828. {
  829. "Total": 1,
  830. "Threshold": 1
  831. }
  832. ]
  833. }
  834. ]
  835. }
  836. `
  837. propagationChannelID, _ := common.MakeRandomStringHex(8)
  838. now := time.Now().UTC()
  839. epoch := now.Truncate(720 * time.Hour)
  840. epochStr := epoch.Format(time.RFC3339Nano)
  841. oslConfigJSON := fmt.Sprintf(
  842. oslConfigJSONFormat,
  843. epochStr, propagationChannelID,
  844. epochStr, propagationChannelID)
  845. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  846. if err != nil {
  847. t.Fatalf("error paving osl config file: %s", err)
  848. }
  849. return propagationChannelID
  850. }