server_test.go 22 KB

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