server_test.go 24 KB

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