server_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. // Set this parameter so at least the semaphore functions are called.
  304. // TODO: test that the concurrency limit is correctly enforced.
  305. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  306. serverConfigJSON, _ = json.Marshal(serverConfig)
  307. // run server
  308. serverWaitGroup := new(sync.WaitGroup)
  309. serverWaitGroup.Add(1)
  310. go func() {
  311. defer serverWaitGroup.Done()
  312. err := RunServices(serverConfigJSON)
  313. if err != nil {
  314. // TODO: wrong goroutine for t.FatalNow()
  315. t.Fatalf("error running server: %s", err)
  316. }
  317. }()
  318. defer func() {
  319. // Test: orderly server shutdown
  320. p, _ := os.FindProcess(os.Getpid())
  321. p.Signal(os.Interrupt)
  322. shutdownTimeout := time.NewTimer(5 * time.Second)
  323. shutdownOk := make(chan struct{}, 1)
  324. go func() {
  325. serverWaitGroup.Wait()
  326. shutdownOk <- *new(struct{})
  327. }()
  328. select {
  329. case <-shutdownOk:
  330. case <-shutdownTimeout.C:
  331. t.Fatalf("server shutdown timeout exceeded")
  332. }
  333. }()
  334. // TODO: monitor logs for more robust wait-until-loaded
  335. time.Sleep(1 * time.Second)
  336. // Test: hot reload (of psinet and traffic rules)
  337. if runConfig.doHotReload {
  338. // Pave new config files with different random values.
  339. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  340. t, runConfig.doDefaultSessionID, psinetFilename)
  341. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  342. paveTrafficRulesFile(
  343. t, trafficRulesFilename, propagationChannelID, runConfig.denyTrafficRules)
  344. p, _ := os.FindProcess(os.Getpid())
  345. p.Signal(syscall.SIGUSR1)
  346. // TODO: monitor logs for more robust wait-until-reloaded
  347. time.Sleep(1 * time.Second)
  348. // After reloading psinet, the new sponsorID/expectedHomepageURL
  349. // should be active, as tested in the client "Homepage" notice
  350. // handler below.
  351. }
  352. // Exercise server_load logging
  353. p, _ := os.FindProcess(os.Getpid())
  354. p.Signal(syscall.SIGUSR2)
  355. // connect to server with client
  356. // TODO: currently, TargetServerEntry only works with one tunnel
  357. numTunnels := 1
  358. localSOCKSProxyPort := 1081
  359. localHTTPProxyPort := 8081
  360. establishTunnelPausePeriodSeconds := 1
  361. // Note: calling LoadConfig ensures all *int config fields are initialized
  362. clientConfigJSON := `
  363. {
  364. "ClientPlatform" : "Windows",
  365. "ClientVersion" : "0",
  366. "SponsorId" : "0",
  367. "PropagationChannelId" : "0",
  368. "DisableRemoteServerListFetcher" : true,
  369. "UseIndistinguishableTLS" : true
  370. }`
  371. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  372. if !runConfig.doDefaultSessionID {
  373. clientConfig.SponsorId = sponsorID
  374. }
  375. clientConfig.PropagationChannelId = propagationChannelID
  376. clientConfig.ConnectionWorkerPoolSize = numTunnels
  377. clientConfig.TunnelPoolSize = numTunnels
  378. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  379. clientConfig.TargetServerEntry = string(encodedServerEntry)
  380. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  381. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  382. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  383. clientConfig.EmitSLOKs = true
  384. if runConfig.doClientVerification {
  385. clientConfig.ClientPlatform = "Android"
  386. }
  387. clientConfig.DataStoreDirectory = testDataDirName
  388. err = psiphon.InitDataStore(clientConfig)
  389. if err != nil {
  390. t.Fatalf("error initializing client datastore: %s", err)
  391. }
  392. psiphon.DeleteSLOKs()
  393. controller, err := psiphon.NewController(clientConfig)
  394. if err != nil {
  395. t.Fatalf("error creating client controller: %s", err)
  396. }
  397. tunnelsEstablished := make(chan struct{}, 1)
  398. homepageReceived := make(chan struct{}, 1)
  399. slokSeeded := make(chan struct{}, 1)
  400. verificationRequired := make(chan struct{}, 1)
  401. verificationCompleted := make(chan struct{}, 1)
  402. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  403. func(notice []byte) {
  404. //fmt.Printf("%s\n", string(notice))
  405. noticeType, payload, err := psiphon.GetNotice(notice)
  406. if err != nil {
  407. return
  408. }
  409. switch noticeType {
  410. case "Tunnels":
  411. // Do not set verification payload until tunnel is
  412. // established. Otherwise will silently take no action.
  413. controller.SetClientVerificationPayloadForActiveTunnels("")
  414. count := int(payload["count"].(float64))
  415. if count >= numTunnels {
  416. sendNotificationReceived(tunnelsEstablished)
  417. }
  418. case "Homepage":
  419. homepageURL := payload["url"].(string)
  420. if homepageURL != expectedHomepageURL {
  421. // TODO: wrong goroutine for t.FatalNow()
  422. t.Fatalf("unexpected homepage: %s", homepageURL)
  423. }
  424. sendNotificationReceived(homepageReceived)
  425. case "SLOKSeeded":
  426. sendNotificationReceived(slokSeeded)
  427. case "ClientVerificationRequired":
  428. sendNotificationReceived(verificationRequired)
  429. controller.SetClientVerificationPayloadForActiveTunnels(dummyClientVerificationPayload)
  430. case "NoticeClientVerificationRequestCompleted":
  431. sendNotificationReceived(verificationCompleted)
  432. }
  433. }))
  434. ctx, cancelFunc := context.WithCancel(context.Background())
  435. controllerWaitGroup := new(sync.WaitGroup)
  436. controllerWaitGroup.Add(1)
  437. go func() {
  438. defer controllerWaitGroup.Done()
  439. controller.Run(ctx)
  440. }()
  441. defer func() {
  442. cancelFunc()
  443. shutdownTimeout := time.NewTimer(20 * time.Second)
  444. shutdownOk := make(chan struct{}, 1)
  445. go func() {
  446. controllerWaitGroup.Wait()
  447. shutdownOk <- *new(struct{})
  448. }()
  449. select {
  450. case <-shutdownOk:
  451. case <-shutdownTimeout.C:
  452. t.Fatalf("controller shutdown timeout exceeded")
  453. }
  454. }()
  455. // Test: tunnels must be established, and correct homepage
  456. // must be received, within 30 seconds
  457. timeoutSignal := make(chan struct{})
  458. go func() {
  459. timer := time.NewTimer(30 * time.Second)
  460. <-timer.C
  461. close(timeoutSignal)
  462. }()
  463. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  464. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  465. if runConfig.doClientVerification {
  466. waitOnNotification(t, verificationRequired, timeoutSignal, "verification required timeout exceeded")
  467. waitOnNotification(t, verificationCompleted, timeoutSignal, "verification completed timeout exceeded")
  468. }
  469. if runConfig.doTunneledWebRequest {
  470. // Test: tunneled web site fetch
  471. err = makeTunneledWebRequest(
  472. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  473. if err == nil {
  474. if runConfig.denyTrafficRules {
  475. t.Fatalf("unexpected tunneled web request success")
  476. }
  477. } else {
  478. if !runConfig.denyTrafficRules {
  479. t.Fatalf("tunneled web request failed: %s", err)
  480. }
  481. }
  482. }
  483. if runConfig.doTunneledNTPRequest {
  484. // Test: tunneled UDP packets
  485. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  486. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  487. if err == nil {
  488. if runConfig.denyTrafficRules {
  489. t.Fatalf("unexpected tunneled NTP request success")
  490. }
  491. } else {
  492. if !runConfig.denyTrafficRules {
  493. t.Fatalf("tunneled NTP request failed: %s", err)
  494. }
  495. }
  496. }
  497. // Test: await SLOK payload
  498. if !runConfig.denyTrafficRules {
  499. time.Sleep(1 * time.Second)
  500. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  501. numSLOKs := psiphon.CountSLOKs()
  502. if numSLOKs != expectedNumSLOKs {
  503. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  504. }
  505. }
  506. }
  507. func makeTunneledWebRequest(
  508. t *testing.T,
  509. localHTTPProxyPort int,
  510. requestURL, expectedResponseBody string) error {
  511. roundTripTimeout := 30 * time.Second
  512. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  513. if err != nil {
  514. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  515. }
  516. httpClient := &http.Client{
  517. Transport: &http.Transport{
  518. Proxy: http.ProxyURL(proxyUrl),
  519. },
  520. Timeout: roundTripTimeout,
  521. }
  522. response, err := httpClient.Get(requestURL)
  523. if err != nil {
  524. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  525. }
  526. body, err := ioutil.ReadAll(response.Body)
  527. if err != nil {
  528. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  529. }
  530. response.Body.Close()
  531. if string(body) != expectedResponseBody {
  532. return fmt.Errorf("unexpected proxied HTTP response")
  533. }
  534. return nil
  535. }
  536. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  537. timeout := 20 * time.Second
  538. var err error
  539. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  540. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  541. if err == nil {
  542. break
  543. }
  544. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  545. }
  546. return err
  547. }
  548. var nextUDPProxyPort = 7300
  549. func makeTunneledNTPRequestAttempt(
  550. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  551. nextUDPProxyPort++
  552. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  553. if err != nil {
  554. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  555. }
  556. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  557. // handles it, and then terminates.
  558. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  559. if waitGroup != nil {
  560. defer waitGroup.Done()
  561. }
  562. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  563. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  564. if err != nil {
  565. t.Logf("ListenUDP for %s failed: %s", destination, err)
  566. return
  567. }
  568. defer serverUDPConn.Close()
  569. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  570. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  571. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  572. buffer[udpgwPreambleSize:])
  573. if err != nil {
  574. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  575. return
  576. }
  577. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  578. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  579. if err != nil {
  580. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  581. return
  582. }
  583. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  584. if err != nil {
  585. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  586. return
  587. }
  588. defer socksTCPConn.Close()
  589. flags := uint8(0)
  590. if destinationPort == 53 {
  591. flags = udpgwProtocolFlagDNS
  592. }
  593. err = writeUdpgwPreamble(
  594. udpgwPreambleSize,
  595. flags,
  596. 0,
  597. destinationIP,
  598. destinationPort,
  599. uint16(packetSize),
  600. buffer)
  601. if err != nil {
  602. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  603. return
  604. }
  605. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  606. if err != nil {
  607. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  608. return
  609. }
  610. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  611. if err != nil {
  612. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  613. return
  614. }
  615. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  616. if err != nil {
  617. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  618. return
  619. }
  620. }
  621. // Tunneled DNS request
  622. waitGroup := new(sync.WaitGroup)
  623. waitGroup.Add(1)
  624. go localUDPProxy(
  625. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  626. 53,
  627. waitGroup)
  628. // TODO: properly synchronize with local UDP proxy startup
  629. time.Sleep(1 * time.Second)
  630. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  631. if err != nil {
  632. return fmt.Errorf("DialUDP failed: %s", err)
  633. }
  634. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  635. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  636. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  637. clientUDPConn.Close()
  638. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  639. err = errors.New("no address")
  640. }
  641. if err != nil {
  642. return fmt.Errorf("ResolveIP failed: %s", err)
  643. }
  644. waitGroup.Wait()
  645. // Tunneled NTP request
  646. waitGroup = new(sync.WaitGroup)
  647. waitGroup.Add(1)
  648. go localUDPProxy(
  649. addrs[0][len(addrs[0])-4:],
  650. 123,
  651. waitGroup)
  652. // TODO: properly synchronize with local UDP proxy startup
  653. time.Sleep(1 * time.Second)
  654. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  655. if err != nil {
  656. return fmt.Errorf("DialUDP failed: %s", err)
  657. }
  658. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  659. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  660. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  661. ntpData := make([]byte, 48)
  662. ntpData[0] = 3<<3 | 3
  663. _, err = clientUDPConn.Write(ntpData)
  664. if err != nil {
  665. clientUDPConn.Close()
  666. return fmt.Errorf("NTP Write failed: %s", err)
  667. }
  668. _, err = clientUDPConn.Read(ntpData)
  669. if err != nil {
  670. clientUDPConn.Close()
  671. return fmt.Errorf("NTP Read failed: %s", err)
  672. }
  673. clientUDPConn.Close()
  674. var sec, frac uint64
  675. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  676. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  677. nsec := sec * 1e9
  678. nsec += (frac * 1e9) >> 32
  679. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  680. now := time.Now()
  681. diff := ntpNow.Sub(now)
  682. if diff < 0 {
  683. diff = -diff
  684. }
  685. if diff > 1*time.Minute {
  686. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  687. }
  688. waitGroup.Wait()
  689. return nil
  690. }
  691. func pavePsinetDatabaseFile(
  692. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  693. sponsorID, _ := common.MakeRandomStringHex(8)
  694. fakeDomain, _ := common.MakeRandomStringHex(4)
  695. fakePath, _ := common.MakeRandomStringHex(4)
  696. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  697. psinetJSONFormat := `
  698. {
  699. "default_sponsor_id" : "%s",
  700. "sponsors": {
  701. "%s": {
  702. "home_pages": {
  703. "None": [
  704. {
  705. "region": null,
  706. "url": "%s"
  707. }
  708. ]
  709. }
  710. }
  711. }
  712. }
  713. `
  714. defaultSponsorID := ""
  715. if useDefaultSponsorID {
  716. defaultSponsorID = sponsorID
  717. }
  718. psinetJSON := fmt.Sprintf(
  719. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  720. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  721. if err != nil {
  722. t.Fatalf("error paving psinet database file: %s", err)
  723. }
  724. return sponsorID, expectedHomepageURL
  725. }
  726. func paveTrafficRulesFile(
  727. t *testing.T, trafficRulesFilename, propagationChannelID string, deny bool) {
  728. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  729. allowUDPPorts := "53, 123"
  730. if deny {
  731. allowTCPPorts = "0"
  732. allowUDPPorts = "0"
  733. }
  734. trafficRulesJSONFormat := `
  735. {
  736. "DefaultRules" : {
  737. "RateLimits" : {
  738. "ReadBytesPerSecond": 16384,
  739. "WriteBytesPerSecond": 16384
  740. },
  741. "AllowTCPPorts" : [0],
  742. "AllowUDPPorts" : [0]
  743. },
  744. "FilteredRules" : [
  745. {
  746. "Filter" : {
  747. "HandshakeParameters" : {
  748. "propagation_channel_id" : ["%s"]
  749. }
  750. },
  751. "Rules" : {
  752. "RateLimits" : {
  753. "ReadUnthrottledBytes": 132352,
  754. "WriteUnthrottledBytes": 132352
  755. },
  756. "AllowTCPPorts" : [%s],
  757. "AllowUDPPorts" : [%s]
  758. }
  759. }
  760. ]
  761. }
  762. `
  763. trafficRulesJSON := fmt.Sprintf(
  764. trafficRulesJSONFormat, propagationChannelID, allowTCPPorts, allowUDPPorts)
  765. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  766. if err != nil {
  767. t.Fatalf("error paving traffic rules file: %s", err)
  768. }
  769. }
  770. var expectedNumSLOKs = 3
  771. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  772. oslConfigJSONFormat := `
  773. {
  774. "Schemes" : [
  775. {
  776. "Epoch" : "%s",
  777. "Regions" : [],
  778. "PropagationChannelIDs" : ["%s"],
  779. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  780. "SeedSpecs" : [
  781. {
  782. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  783. "UpstreamSubnets" : ["0.0.0.0/0"],
  784. "Targets" :
  785. {
  786. "BytesRead" : 1,
  787. "BytesWritten" : 1,
  788. "PortForwardDurationNanoseconds" : 1
  789. }
  790. },
  791. {
  792. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  793. "UpstreamSubnets" : ["0.0.0.0/0"],
  794. "Targets" :
  795. {
  796. "BytesRead" : 1,
  797. "BytesWritten" : 1,
  798. "PortForwardDurationNanoseconds" : 1
  799. }
  800. }
  801. ],
  802. "SeedSpecThreshold" : 2,
  803. "SeedPeriodNanoseconds" : 2592000000000000,
  804. "SeedPeriodKeySplits": [
  805. {
  806. "Total": 2,
  807. "Threshold": 2
  808. }
  809. ]
  810. },
  811. {
  812. "Epoch" : "%s",
  813. "Regions" : [],
  814. "PropagationChannelIDs" : ["%s"],
  815. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  816. "SeedSpecs" : [
  817. {
  818. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  819. "UpstreamSubnets" : ["0.0.0.0/0"],
  820. "Targets" :
  821. {
  822. "BytesRead" : 1,
  823. "BytesWritten" : 1,
  824. "PortForwardDurationNanoseconds" : 1
  825. }
  826. }
  827. ],
  828. "SeedSpecThreshold" : 1,
  829. "SeedPeriodNanoseconds" : 2592000000000000,
  830. "SeedPeriodKeySplits": [
  831. {
  832. "Total": 1,
  833. "Threshold": 1
  834. }
  835. ]
  836. }
  837. ]
  838. }
  839. `
  840. propagationChannelID, _ := common.MakeRandomStringHex(8)
  841. now := time.Now().UTC()
  842. epoch := now.Truncate(720 * time.Hour)
  843. epochStr := epoch.Format(time.RFC3339Nano)
  844. oslConfigJSON := fmt.Sprintf(
  845. oslConfigJSONFormat,
  846. epochStr, propagationChannelID,
  847. epochStr, propagationChannelID)
  848. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  849. if err != nil {
  850. t.Fatalf("error paving osl config file: %s", err)
  851. }
  852. return propagationChannelID
  853. }