server_test.go 24 KB

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