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. // Test: hot reload (of psinet and traffic rules)
  262. if runConfig.doHotReload {
  263. // TODO: monitor logs for more robust wait-until-loaded
  264. time.Sleep(1 * time.Second)
  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. time.Sleep(1 * time.Second)
  280. // connect to server with client
  281. // TODO: currently, TargetServerEntry only works with one tunnel
  282. numTunnels := 1
  283. localSOCKSProxyPort := 1081
  284. localHTTPProxyPort := 8081
  285. establishTunnelPausePeriodSeconds := 1
  286. // Note: calling LoadConfig ensures all *int config fields are initialized
  287. clientConfigJSON := `
  288. {
  289. "ClientPlatform" : "Windows",
  290. "ClientVersion" : "0",
  291. "SponsorId" : "0",
  292. "PropagationChannelId" : "0",
  293. "DisableRemoteServerListFetcher" : true
  294. }`
  295. clientConfig, _ := psiphon.LoadConfig([]byte(clientConfigJSON))
  296. clientConfig.SponsorId = sponsorID
  297. clientConfig.PropagationChannelId = propagationChannelID
  298. clientConfig.ConnectionWorkerPoolSize = numTunnels
  299. clientConfig.TunnelPoolSize = numTunnels
  300. clientConfig.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  301. clientConfig.TargetServerEntry = string(encodedServerEntry)
  302. clientConfig.TunnelProtocol = runConfig.tunnelProtocol
  303. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  304. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  305. clientConfig.EmitSLOKs = true
  306. if runConfig.doClientVerification {
  307. clientConfig.ClientPlatform = "Android"
  308. }
  309. clientConfig.DataStoreDirectory = testDataDirName
  310. err = psiphon.InitDataStore(clientConfig)
  311. if err != nil {
  312. t.Fatalf("error initializing client datastore: %s", err)
  313. }
  314. controller, err := psiphon.NewController(clientConfig)
  315. if err != nil {
  316. t.Fatalf("error creating client controller: %s", err)
  317. }
  318. tunnelsEstablished := make(chan struct{}, 1)
  319. homepageReceived := make(chan struct{}, 1)
  320. slokSeeded := make(chan struct{}, 1)
  321. verificationRequired := make(chan struct{}, 1)
  322. verificationCompleted := make(chan struct{}, 1)
  323. psiphon.SetNoticeOutput(psiphon.NewNoticeReceiver(
  324. func(notice []byte) {
  325. //fmt.Printf("%s\n", string(notice))
  326. noticeType, payload, err := psiphon.GetNotice(notice)
  327. if err != nil {
  328. return
  329. }
  330. switch noticeType {
  331. case "Tunnels":
  332. // Do not set verification payload until tunnel is
  333. // established. Otherwise will silently take no action.
  334. controller.SetClientVerificationPayloadForActiveTunnels("")
  335. count := int(payload["count"].(float64))
  336. if count >= numTunnels {
  337. sendNotificationReceived(tunnelsEstablished)
  338. }
  339. case "Homepage":
  340. homepageURL := payload["url"].(string)
  341. if homepageURL != expectedHomepageURL {
  342. // TODO: wrong goroutine for t.FatalNow()
  343. t.Fatalf("unexpected homepage: %s", homepageURL)
  344. }
  345. sendNotificationReceived(homepageReceived)
  346. case "SLOKSeeded":
  347. sendNotificationReceived(slokSeeded)
  348. case "ClientVerificationRequired":
  349. sendNotificationReceived(verificationRequired)
  350. controller.SetClientVerificationPayloadForActiveTunnels(dummyClientVerificationPayload)
  351. case "NoticeClientVerificationRequestCompleted":
  352. sendNotificationReceived(verificationCompleted)
  353. }
  354. }))
  355. controllerShutdownBroadcast := make(chan struct{})
  356. controllerWaitGroup := new(sync.WaitGroup)
  357. controllerWaitGroup.Add(1)
  358. go func() {
  359. defer controllerWaitGroup.Done()
  360. controller.Run(controllerShutdownBroadcast)
  361. }()
  362. defer func() {
  363. close(controllerShutdownBroadcast)
  364. shutdownTimeout := time.NewTimer(20 * time.Second)
  365. shutdownOk := make(chan struct{}, 1)
  366. go func() {
  367. controllerWaitGroup.Wait()
  368. shutdownOk <- *new(struct{})
  369. }()
  370. select {
  371. case <-shutdownOk:
  372. case <-shutdownTimeout.C:
  373. t.Fatalf("controller shutdown timeout exceeded")
  374. }
  375. }()
  376. // Test: tunnels must be established, and correct homepage
  377. // must be received, within 30 seconds
  378. timeoutSignal := make(chan struct{})
  379. go func() {
  380. timer := time.NewTimer(30 * time.Second)
  381. <-timer.C
  382. close(timeoutSignal)
  383. }()
  384. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  385. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  386. if runConfig.doClientVerification {
  387. waitOnNotification(t, verificationRequired, timeoutSignal, "verification required timeout exceeded")
  388. waitOnNotification(t, verificationCompleted, timeoutSignal, "verification completed timeout exceeded")
  389. }
  390. if runConfig.doTunneledWebRequest {
  391. // Test: tunneled web site fetch
  392. err = makeTunneledWebRequest(t, localHTTPProxyPort)
  393. if err == nil {
  394. if runConfig.denyTrafficRules {
  395. t.Fatalf("unexpected tunneled web request success")
  396. }
  397. } else {
  398. if !runConfig.denyTrafficRules {
  399. t.Fatalf("tunneled web request failed: %s", err)
  400. }
  401. }
  402. }
  403. if runConfig.doTunneledNTPRequest {
  404. // Test: tunneled UDP packets
  405. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  406. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  407. if err == nil {
  408. if runConfig.denyTrafficRules {
  409. t.Fatalf("unexpected tunneled NTP request success")
  410. }
  411. } else {
  412. if !runConfig.denyTrafficRules {
  413. t.Fatalf("tunneled NTP request failed: %s", err)
  414. }
  415. }
  416. }
  417. // Test: await SLOK payload
  418. if !runConfig.denyTrafficRules {
  419. time.Sleep(1 * time.Second)
  420. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  421. }
  422. }
  423. func makeTunneledWebRequest(t *testing.T, localHTTPProxyPort int) error {
  424. testUrl := "https://psiphon.ca"
  425. roundTripTimeout := 30 * time.Second
  426. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  427. if err != nil {
  428. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  429. }
  430. httpClient := &http.Client{
  431. Transport: &http.Transport{
  432. Proxy: http.ProxyURL(proxyUrl),
  433. },
  434. Timeout: roundTripTimeout,
  435. }
  436. response, err := httpClient.Get(testUrl)
  437. if err != nil {
  438. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  439. }
  440. _, err = ioutil.ReadAll(response.Body)
  441. if err != nil {
  442. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  443. }
  444. response.Body.Close()
  445. return nil
  446. }
  447. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  448. testHostname := "pool.ntp.org"
  449. timeout := 10 * time.Second
  450. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", "127.0.0.1:7301")
  451. if err != nil {
  452. t.Fatalf("ResolveUDPAddr failed: %s", err)
  453. }
  454. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  455. // handles it, and then terminates.
  456. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  457. if waitGroup != nil {
  458. defer waitGroup.Done()
  459. }
  460. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  461. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  462. if err != nil {
  463. t.Logf("ListenUDP for %s failed: %s", destination, err)
  464. return
  465. }
  466. defer serverUDPConn.Close()
  467. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  468. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  469. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  470. buffer[udpgwPreambleSize:len(buffer)])
  471. if err != nil {
  472. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  473. return
  474. }
  475. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  476. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  477. if err != nil {
  478. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  479. return
  480. }
  481. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  482. if err != nil {
  483. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  484. return
  485. }
  486. defer socksTCPConn.Close()
  487. flags := uint8(0)
  488. if destinationPort == 53 {
  489. flags = udpgwProtocolFlagDNS
  490. }
  491. err = writeUdpgwPreamble(
  492. udpgwPreambleSize,
  493. flags,
  494. 0,
  495. destinationIP,
  496. destinationPort,
  497. uint16(packetSize),
  498. buffer)
  499. if err != nil {
  500. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  501. return
  502. }
  503. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  504. if err != nil {
  505. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  506. return
  507. }
  508. updgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  509. if err != nil {
  510. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  511. return
  512. }
  513. _, err = serverUDPConn.WriteToUDP(updgwProtocolMessage.packet, clientAddr)
  514. if err != nil {
  515. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  516. return
  517. }
  518. }
  519. // Tunneled DNS request
  520. waitGroup := new(sync.WaitGroup)
  521. waitGroup.Add(1)
  522. go localUDPProxy(
  523. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  524. 53,
  525. waitGroup)
  526. // TODO: properly synchronize with local UDP proxy startup
  527. time.Sleep(1 * time.Second)
  528. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  529. if err != nil {
  530. return fmt.Errorf("DialUDP failed: %s", err)
  531. }
  532. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  533. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  534. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  535. clientUDPConn.Close()
  536. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  537. err = errors.New("no address")
  538. }
  539. if err != nil {
  540. return fmt.Errorf("ResolveIP failed: %s", err)
  541. }
  542. waitGroup.Wait()
  543. // Tunneled NTP request
  544. go localUDPProxy(addrs[0][len(addrs[0])-4:], 123, nil)
  545. // TODO: properly synchronize with local UDP proxy startup
  546. time.Sleep(1 * time.Second)
  547. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  548. if err != nil {
  549. return fmt.Errorf("DialUDP failed: %s", err)
  550. }
  551. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  552. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  553. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  554. ntpData := make([]byte, 48)
  555. ntpData[0] = 3<<3 | 3
  556. _, err = clientUDPConn.Write(ntpData)
  557. if err != nil {
  558. clientUDPConn.Close()
  559. return fmt.Errorf("NTP Write failed: %s", err)
  560. }
  561. _, err = clientUDPConn.Read(ntpData)
  562. if err != nil {
  563. clientUDPConn.Close()
  564. return fmt.Errorf("NTP Read failed: %s", err)
  565. }
  566. clientUDPConn.Close()
  567. var sec, frac uint64
  568. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  569. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  570. nsec := sec * 1e9
  571. nsec += (frac * 1e9) >> 32
  572. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  573. now := time.Now()
  574. diff := ntpNow.Sub(now)
  575. if diff < 0 {
  576. diff = -diff
  577. }
  578. if diff > 1*time.Minute {
  579. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  580. }
  581. return nil
  582. }
  583. func pavePsinetDatabaseFile(t *testing.T, psinetFilename string) (string, string) {
  584. sponsorID, _ := common.MakeRandomStringHex(8)
  585. fakeDomain, _ := common.MakeRandomStringHex(4)
  586. fakePath, _ := common.MakeRandomStringHex(4)
  587. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  588. psinetJSONFormat := `
  589. {
  590. "sponsors": {
  591. "%s": {
  592. "home_pages": {
  593. "None": [
  594. {
  595. "region": null,
  596. "url": "%s"
  597. }
  598. ]
  599. }
  600. }
  601. }
  602. }
  603. `
  604. psinetJSON := fmt.Sprintf(psinetJSONFormat, sponsorID, expectedHomepageURL)
  605. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  606. if err != nil {
  607. t.Fatalf("error paving psinet database file: %s", err)
  608. }
  609. return sponsorID, expectedHomepageURL
  610. }
  611. func paveTrafficRulesFile(t *testing.T, trafficRulesFilename, sponsorID string, deny bool) {
  612. allowTCPPorts := "443"
  613. allowUDPPorts := "53, 123"
  614. if deny {
  615. allowTCPPorts = "0"
  616. allowUDPPorts = "0"
  617. }
  618. trafficRulesJSONFormat := `
  619. {
  620. "DefaultRules" : {
  621. "RateLimits" : {
  622. "ReadBytesPerSecond": 16384,
  623. "WriteBytesPerSecond": 16384
  624. },
  625. "AllowTCPPorts" : [0],
  626. "AllowUDPPorts" : [0]
  627. },
  628. "FilteredRules" : [
  629. {
  630. "Filter" : {
  631. "HandshakeParameters" : {
  632. "sponsor_id" : ["%s"]
  633. }
  634. },
  635. "Rules" : {
  636. "RateLimits" : {
  637. "ReadUnthrottledBytes": 132352,
  638. "WriteUnthrottledBytes": 132352
  639. },
  640. "AllowTCPPorts" : [%s],
  641. "AllowUDPPorts" : [%s]
  642. }
  643. }
  644. ]
  645. }
  646. `
  647. trafficRulesJSON := fmt.Sprintf(
  648. trafficRulesJSONFormat, sponsorID, allowTCPPorts, allowUDPPorts)
  649. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  650. if err != nil {
  651. t.Fatalf("error paving traffic rules file: %s", err)
  652. }
  653. }
  654. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  655. oslConfigJSONFormat := `
  656. {
  657. "Schemes" : [
  658. {
  659. "Epoch" : "%s",
  660. "Regions" : [],
  661. "PropagationChannelIDs" : ["%s"],
  662. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  663. "SeedSpecs" : [
  664. {
  665. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  666. "UpstreamSubnets" : ["0.0.0.0/0"],
  667. "Targets" :
  668. {
  669. "BytesRead" : 1,
  670. "BytesWritten" : 1,
  671. "PortForwardDurationNanoseconds" : 1
  672. }
  673. },
  674. {
  675. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  676. "UpstreamSubnets" : ["0.0.0.0/0"],
  677. "Targets" :
  678. {
  679. "BytesRead" : 1,
  680. "BytesWritten" : 1,
  681. "PortForwardDurationNanoseconds" : 1
  682. }
  683. }
  684. ],
  685. "SeedSpecThreshold" : 2,
  686. "SeedPeriodNanoseconds" : 10000000000,
  687. "SeedPeriodKeySplits": [
  688. {
  689. "Total": 2,
  690. "Threshold": 2
  691. }
  692. ]
  693. }
  694. ]
  695. }
  696. `
  697. propagationChannelID, _ := common.MakeRandomStringHex(8)
  698. now := time.Now().UTC()
  699. epoch := now.Truncate(10 * time.Second)
  700. epochStr := epoch.Format(time.RFC3339Nano)
  701. oslConfigJSON := fmt.Sprintf(
  702. oslConfigJSONFormat, epochStr, propagationChannelID)
  703. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  704. if err != nil {
  705. t.Fatalf("error paving osl config file: %s", err)
  706. }
  707. return propagationChannelID
  708. }