server_test.go 24 KB

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