server_test.go 27 KB

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