server_test.go 25 KB

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