server_test.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. "context"
  22. "encoding/json"
  23. "errors"
  24. "flag"
  25. "fmt"
  26. "io/ioutil"
  27. "net"
  28. "net/http"
  29. "net/url"
  30. "os"
  31. "path/filepath"
  32. "strconv"
  33. "sync"
  34. "syscall"
  35. "testing"
  36. "time"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  44. "golang.org/x/net/proxy"
  45. )
  46. var serverIPAddress, testDataDirName string
  47. var mockWebServerURL, mockWebServerExpectedResponse string
  48. var mockWebServerPort = 8080
  49. func TestMain(m *testing.M) {
  50. flag.Parse()
  51. var err error
  52. for _, interfaceName := range []string{"eth0", "en0"} {
  53. var serverIPv4Address, serverIPv6Address net.IP
  54. serverIPv4Address, serverIPv6Address, err = common.GetInterfaceIPAddresses(interfaceName)
  55. if err == nil {
  56. if serverIPv4Address != nil {
  57. serverIPAddress = serverIPv4Address.String()
  58. } else {
  59. serverIPAddress = serverIPv6Address.String()
  60. }
  61. break
  62. }
  63. }
  64. if err != nil {
  65. fmt.Printf("error getting server IP address: %s\n", err)
  66. os.Exit(1)
  67. }
  68. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  69. if err != nil {
  70. fmt.Printf("TempDir failed: %s\n", err)
  71. os.Exit(1)
  72. }
  73. defer os.RemoveAll(testDataDirName)
  74. psiphon.SetEmitDiagnosticNotices(true)
  75. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  76. os.Exit(m.Run())
  77. }
  78. func runMockWebServer() (string, string) {
  79. responseBody, _ := common.MakeSecureRandomStringHex(100000)
  80. serveMux := http.NewServeMux()
  81. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  82. w.Write([]byte(responseBody))
  83. })
  84. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  85. server := &http.Server{
  86. Addr: webServerAddress,
  87. Handler: serveMux,
  88. }
  89. go func() {
  90. err := server.ListenAndServe()
  91. if err != nil {
  92. fmt.Printf("error running mock web server: %s\n", err)
  93. os.Exit(1)
  94. }
  95. }()
  96. // TODO: properly synchronize with web server readiness
  97. time.Sleep(1 * time.Second)
  98. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  99. }
  100. // Note: not testing fronting meek protocols, which client is
  101. // hard-wired to except running on privileged ports 80 and 443.
  102. func TestSSH(t *testing.T) {
  103. runServer(t,
  104. &runServerConfig{
  105. tunnelProtocol: "SSH",
  106. enableSSHAPIRequests: true,
  107. doHotReload: false,
  108. doDefaultSponsorID: false,
  109. denyTrafficRules: false,
  110. requireAuthorization: true,
  111. omitAuthorization: false,
  112. doTunneledWebRequest: true,
  113. doTunneledNTPRequest: true,
  114. })
  115. }
  116. func TestOSSH(t *testing.T) {
  117. runServer(t,
  118. &runServerConfig{
  119. tunnelProtocol: "OSSH",
  120. enableSSHAPIRequests: true,
  121. doHotReload: false,
  122. doDefaultSponsorID: false,
  123. denyTrafficRules: false,
  124. requireAuthorization: true,
  125. omitAuthorization: false,
  126. doTunneledWebRequest: true,
  127. doTunneledNTPRequest: true,
  128. })
  129. }
  130. func TestUnfrontedMeek(t *testing.T) {
  131. runServer(t,
  132. &runServerConfig{
  133. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  134. enableSSHAPIRequests: true,
  135. doHotReload: false,
  136. doDefaultSponsorID: false,
  137. denyTrafficRules: false,
  138. requireAuthorization: true,
  139. omitAuthorization: false,
  140. doTunneledWebRequest: true,
  141. doTunneledNTPRequest: true,
  142. })
  143. }
  144. func TestUnfrontedMeekHTTPS(t *testing.T) {
  145. runServer(t,
  146. &runServerConfig{
  147. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  148. enableSSHAPIRequests: true,
  149. doHotReload: false,
  150. doDefaultSponsorID: false,
  151. denyTrafficRules: false,
  152. requireAuthorization: true,
  153. omitAuthorization: false,
  154. doTunneledWebRequest: true,
  155. doTunneledNTPRequest: true,
  156. })
  157. }
  158. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  159. runServer(t,
  160. &runServerConfig{
  161. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  162. enableSSHAPIRequests: true,
  163. doHotReload: false,
  164. doDefaultSponsorID: false,
  165. denyTrafficRules: false,
  166. requireAuthorization: true,
  167. omitAuthorization: false,
  168. doTunneledWebRequest: true,
  169. doTunneledNTPRequest: true,
  170. })
  171. }
  172. func TestQUICOSSH(t *testing.T) {
  173. runServer(t,
  174. &runServerConfig{
  175. tunnelProtocol: "QUIC-OSSH",
  176. enableSSHAPIRequests: true,
  177. doHotReload: false,
  178. doDefaultSponsorID: false,
  179. denyTrafficRules: false,
  180. requireAuthorization: true,
  181. omitAuthorization: false,
  182. doTunneledWebRequest: true,
  183. doTunneledNTPRequest: true,
  184. })
  185. }
  186. func TestMarionetteOSSH(t *testing.T) {
  187. if !marionette.Enabled() {
  188. t.Skip("Marionette is not enabled")
  189. }
  190. runServer(t,
  191. &runServerConfig{
  192. tunnelProtocol: "MARIONETTE-OSSH",
  193. enableSSHAPIRequests: true,
  194. doHotReload: false,
  195. doDefaultSponsorID: false,
  196. denyTrafficRules: false,
  197. requireAuthorization: true,
  198. omitAuthorization: false,
  199. doTunneledWebRequest: true,
  200. doTunneledNTPRequest: true,
  201. })
  202. }
  203. func TestWebTransportAPIRequests(t *testing.T) {
  204. runServer(t,
  205. &runServerConfig{
  206. tunnelProtocol: "OSSH",
  207. enableSSHAPIRequests: false,
  208. doHotReload: false,
  209. doDefaultSponsorID: false,
  210. denyTrafficRules: false,
  211. requireAuthorization: false,
  212. omitAuthorization: true,
  213. doTunneledWebRequest: true,
  214. doTunneledNTPRequest: true,
  215. })
  216. }
  217. func TestHotReload(t *testing.T) {
  218. runServer(t,
  219. &runServerConfig{
  220. tunnelProtocol: "OSSH",
  221. enableSSHAPIRequests: true,
  222. doHotReload: true,
  223. doDefaultSponsorID: false,
  224. denyTrafficRules: false,
  225. requireAuthorization: true,
  226. omitAuthorization: false,
  227. doTunneledWebRequest: true,
  228. doTunneledNTPRequest: true,
  229. })
  230. }
  231. func TestDefaultSessionID(t *testing.T) {
  232. runServer(t,
  233. &runServerConfig{
  234. tunnelProtocol: "OSSH",
  235. enableSSHAPIRequests: true,
  236. doHotReload: true,
  237. doDefaultSponsorID: true,
  238. denyTrafficRules: false,
  239. requireAuthorization: true,
  240. omitAuthorization: false,
  241. doTunneledWebRequest: true,
  242. doTunneledNTPRequest: true,
  243. })
  244. }
  245. func TestDenyTrafficRules(t *testing.T) {
  246. runServer(t,
  247. &runServerConfig{
  248. tunnelProtocol: "OSSH",
  249. enableSSHAPIRequests: true,
  250. doHotReload: true,
  251. doDefaultSponsorID: false,
  252. denyTrafficRules: true,
  253. requireAuthorization: true,
  254. omitAuthorization: false,
  255. doTunneledWebRequest: true,
  256. doTunneledNTPRequest: true,
  257. })
  258. }
  259. func TestOmitAuthorization(t *testing.T) {
  260. runServer(t,
  261. &runServerConfig{
  262. tunnelProtocol: "OSSH",
  263. enableSSHAPIRequests: true,
  264. doHotReload: true,
  265. doDefaultSponsorID: false,
  266. denyTrafficRules: false,
  267. requireAuthorization: true,
  268. omitAuthorization: true,
  269. doTunneledWebRequest: true,
  270. doTunneledNTPRequest: true,
  271. })
  272. }
  273. func TestNoAuthorization(t *testing.T) {
  274. runServer(t,
  275. &runServerConfig{
  276. tunnelProtocol: "OSSH",
  277. enableSSHAPIRequests: true,
  278. doHotReload: true,
  279. doDefaultSponsorID: false,
  280. denyTrafficRules: false,
  281. requireAuthorization: false,
  282. omitAuthorization: true,
  283. doTunneledWebRequest: true,
  284. doTunneledNTPRequest: true,
  285. })
  286. }
  287. func TestUnusedAuthorization(t *testing.T) {
  288. runServer(t,
  289. &runServerConfig{
  290. tunnelProtocol: "OSSH",
  291. enableSSHAPIRequests: true,
  292. doHotReload: true,
  293. doDefaultSponsorID: false,
  294. denyTrafficRules: false,
  295. requireAuthorization: false,
  296. omitAuthorization: false,
  297. doTunneledWebRequest: true,
  298. doTunneledNTPRequest: true,
  299. })
  300. }
  301. func TestTCPOnlySLOK(t *testing.T) {
  302. runServer(t,
  303. &runServerConfig{
  304. tunnelProtocol: "OSSH",
  305. enableSSHAPIRequests: true,
  306. doHotReload: false,
  307. doDefaultSponsorID: false,
  308. denyTrafficRules: false,
  309. requireAuthorization: true,
  310. omitAuthorization: false,
  311. doTunneledWebRequest: true,
  312. doTunneledNTPRequest: false,
  313. })
  314. }
  315. func TestUDPOnlySLOK(t *testing.T) {
  316. runServer(t,
  317. &runServerConfig{
  318. tunnelProtocol: "OSSH",
  319. enableSSHAPIRequests: true,
  320. doHotReload: false,
  321. doDefaultSponsorID: false,
  322. denyTrafficRules: false,
  323. requireAuthorization: true,
  324. omitAuthorization: false,
  325. doTunneledWebRequest: false,
  326. doTunneledNTPRequest: true,
  327. })
  328. }
  329. type runServerConfig struct {
  330. tunnelProtocol string
  331. enableSSHAPIRequests bool
  332. doHotReload bool
  333. doDefaultSponsorID bool
  334. denyTrafficRules bool
  335. requireAuthorization bool
  336. omitAuthorization bool
  337. doTunneledWebRequest bool
  338. doTunneledNTPRequest bool
  339. }
  340. func runServer(t *testing.T, runConfig *runServerConfig) {
  341. // configure authorized access
  342. accessType := "test-access-type"
  343. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  344. if err != nil {
  345. t.Fatalf("error creating access control key pair: %s", err)
  346. }
  347. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  348. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  349. }
  350. var authorizationID [32]byte
  351. clientAuthorization, err := accesscontrol.IssueAuthorization(
  352. accessControlSigningKey,
  353. authorizationID[:],
  354. time.Now().Add(1*time.Hour))
  355. if err != nil {
  356. t.Fatalf("error issuing authorization: %s", err)
  357. }
  358. // Enable tactics when the test protocol is meek. Both the client and the
  359. // server will be configured to support tactics. The client config will be
  360. // set with a nonfunctional config so that the tactics request must
  361. // succeed, overriding the nonfunctional values, for the tunnel to
  362. // establish.
  363. doTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  364. // All servers require a tactics config with valid keys.
  365. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  366. tactics.GenerateKeys()
  367. if err != nil {
  368. t.Fatalf("error generating tactics keys: %s", err)
  369. }
  370. // create a server
  371. psiphonServerIPAddress := serverIPAddress
  372. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) ||
  373. protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  374. // Workaround for macOS firewall.
  375. psiphonServerIPAddress = "127.0.0.1"
  376. }
  377. generateConfigParams := &GenerateConfigParams{
  378. ServerIPAddress: psiphonServerIPAddress,
  379. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  380. WebServerPort: 8000,
  381. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  382. }
  383. if protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  384. generateConfigParams.TunnelProtocolPorts[runConfig.tunnelProtocol] = 0
  385. generateConfigParams.MarionetteFormat = "http_simple_nonblocking"
  386. }
  387. if doTactics {
  388. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  389. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  390. }
  391. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  392. if err != nil {
  393. t.Fatalf("error generating server config: %s", err)
  394. }
  395. // customize server config
  396. // Pave psinet with random values to test handshake homepages.
  397. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  398. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  399. t, runConfig.doDefaultSponsorID, psinetFilename)
  400. // Pave OSL config for SLOK testing
  401. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  402. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  403. // Pave traffic rules file which exercises handshake parameter filtering. Client
  404. // must handshake with specified sponsor ID in order to allow ports for tunneled
  405. // requests.
  406. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  407. paveTrafficRulesFile(
  408. t, trafficRulesFilename, propagationChannelID, accessType,
  409. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  410. var tacticsConfigFilename string
  411. // Only pave the tactics config when tactics are required. This exercises the
  412. // case where the tactics config is omitted.
  413. if doTactics {
  414. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  415. paveTacticsConfigFile(
  416. t, tacticsConfigFilename,
  417. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  418. runConfig.tunnelProtocol,
  419. propagationChannelID)
  420. }
  421. var serverConfig map[string]interface{}
  422. json.Unmarshal(serverConfigJSON, &serverConfig)
  423. serverConfig["GeoIPDatabaseFilename"] = ""
  424. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  425. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  426. serverConfig["OSLConfigFilename"] = oslConfigFilename
  427. if doTactics {
  428. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  429. }
  430. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  431. serverConfig["LogLevel"] = "debug"
  432. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  433. // Set this parameter so at least the semaphore functions are called.
  434. // TODO: test that the concurrency limit is correctly enforced.
  435. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  436. // Exercise this option.
  437. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  438. serverConfigJSON, _ = json.Marshal(serverConfig)
  439. // run server
  440. serverWaitGroup := new(sync.WaitGroup)
  441. serverWaitGroup.Add(1)
  442. go func() {
  443. defer serverWaitGroup.Done()
  444. err := RunServices(serverConfigJSON)
  445. if err != nil {
  446. // TODO: wrong goroutine for t.FatalNow()
  447. t.Fatalf("error running server: %s", err)
  448. }
  449. }()
  450. defer func() {
  451. // Test: orderly server shutdown
  452. p, _ := os.FindProcess(os.Getpid())
  453. p.Signal(os.Interrupt)
  454. shutdownTimeout := time.NewTimer(5 * time.Second)
  455. shutdownOk := make(chan struct{}, 1)
  456. go func() {
  457. serverWaitGroup.Wait()
  458. shutdownOk <- *new(struct{})
  459. }()
  460. select {
  461. case <-shutdownOk:
  462. case <-shutdownTimeout.C:
  463. t.Fatalf("server shutdown timeout exceeded")
  464. }
  465. }()
  466. // TODO: monitor logs for more robust wait-until-loaded
  467. time.Sleep(1 * time.Second)
  468. // Test: hot reload (of psinet and traffic rules)
  469. if runConfig.doHotReload {
  470. // Pave new config files with different random values.
  471. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  472. t, runConfig.doDefaultSponsorID, psinetFilename)
  473. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  474. paveTrafficRulesFile(
  475. t, trafficRulesFilename, propagationChannelID, accessType,
  476. runConfig.requireAuthorization, runConfig.denyTrafficRules)
  477. p, _ := os.FindProcess(os.Getpid())
  478. p.Signal(syscall.SIGUSR1)
  479. // TODO: monitor logs for more robust wait-until-reloaded
  480. time.Sleep(1 * time.Second)
  481. // After reloading psinet, the new sponsorID/expectedHomepageURL
  482. // should be active, as tested in the client "Homepage" notice
  483. // handler below.
  484. }
  485. // Exercise server_load logging
  486. p, _ := os.FindProcess(os.Getpid())
  487. p.Signal(syscall.SIGUSR2)
  488. // connect to server with client
  489. // TODO: currently, TargetServerEntry only works with one tunnel
  490. numTunnels := 1
  491. localSOCKSProxyPort := 1081
  492. localHTTPProxyPort := 8081
  493. jsonNetworkID := ""
  494. if doTactics {
  495. // Use a distinct prefix for network ID for each test run to
  496. // ensure tactics from different runs don't apply; this is
  497. // a workaround for the singleton datastore.
  498. prefix := time.Now().String()
  499. jsonNetworkID = fmt.Sprintf(`,"NetworkID" : "%s-%s"`, prefix, "NETWORK1")
  500. }
  501. clientConfigJSON := fmt.Sprintf(`
  502. {
  503. "ClientPlatform" : "Windows",
  504. "ClientVersion" : "0",
  505. "SponsorId" : "0",
  506. "PropagationChannelId" : "0",
  507. "DisableRemoteServerListFetcher" : true,
  508. "EstablishTunnelPausePeriodSeconds" : 1,
  509. "ConnectionWorkerPoolSize" : %d,
  510. "LimitTunnelProtocols" : ["%s"]
  511. %s
  512. }`, numTunnels, runConfig.tunnelProtocol, jsonNetworkID)
  513. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  514. if err != nil {
  515. t.Fatalf("error processing configuration file: %s", err)
  516. }
  517. clientConfig.DataStoreDirectory = testDataDirName
  518. if !runConfig.doDefaultSponsorID {
  519. clientConfig.SponsorId = sponsorID
  520. }
  521. clientConfig.PropagationChannelId = propagationChannelID
  522. clientConfig.TunnelPoolSize = numTunnels
  523. clientConfig.TargetServerEntry = string(encodedServerEntry)
  524. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  525. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  526. clientConfig.EmitSLOKs = true
  527. if !runConfig.omitAuthorization {
  528. clientConfig.Authorizations = []string{clientAuthorization}
  529. }
  530. err = clientConfig.Commit()
  531. if err != nil {
  532. t.Fatalf("error committing configuration file: %s", err)
  533. }
  534. if doTactics {
  535. // Configure nonfunctional values that must be overridden by tactics.
  536. applyParameters := make(map[string]interface{})
  537. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  538. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  539. err = clientConfig.SetClientParameters("", true, applyParameters)
  540. if err != nil {
  541. t.Fatalf("SetClientParameters failed: %s", err)
  542. }
  543. }
  544. err = psiphon.OpenDataStore(clientConfig)
  545. if err != nil {
  546. t.Fatalf("error initializing client datastore: %s", err)
  547. }
  548. defer psiphon.CloseDataStore()
  549. psiphon.DeleteSLOKs()
  550. controller, err := psiphon.NewController(clientConfig)
  551. if err != nil {
  552. t.Fatalf("error creating client controller: %s", err)
  553. }
  554. tunnelsEstablished := make(chan struct{}, 1)
  555. homepageReceived := make(chan struct{}, 1)
  556. slokSeeded := make(chan struct{}, 1)
  557. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  558. func(notice []byte) {
  559. //fmt.Printf("%s\n", string(notice))
  560. noticeType, payload, err := psiphon.GetNotice(notice)
  561. if err != nil {
  562. return
  563. }
  564. switch noticeType {
  565. case "Tunnels":
  566. count := int(payload["count"].(float64))
  567. if count >= numTunnels {
  568. sendNotificationReceived(tunnelsEstablished)
  569. }
  570. case "Homepage":
  571. homepageURL := payload["url"].(string)
  572. if homepageURL != expectedHomepageURL {
  573. // TODO: wrong goroutine for t.FatalNow()
  574. t.Fatalf("unexpected homepage: %s", homepageURL)
  575. }
  576. sendNotificationReceived(homepageReceived)
  577. case "SLOKSeeded":
  578. sendNotificationReceived(slokSeeded)
  579. }
  580. }))
  581. ctx, cancelFunc := context.WithCancel(context.Background())
  582. controllerWaitGroup := new(sync.WaitGroup)
  583. controllerWaitGroup.Add(1)
  584. go func() {
  585. defer controllerWaitGroup.Done()
  586. controller.Run(ctx)
  587. }()
  588. defer func() {
  589. cancelFunc()
  590. shutdownTimeout := time.NewTimer(20 * time.Second)
  591. shutdownOk := make(chan struct{}, 1)
  592. go func() {
  593. controllerWaitGroup.Wait()
  594. shutdownOk <- *new(struct{})
  595. }()
  596. select {
  597. case <-shutdownOk:
  598. case <-shutdownTimeout.C:
  599. t.Fatalf("controller shutdown timeout exceeded")
  600. }
  601. }()
  602. // Test: tunnels must be established, and correct homepage
  603. // must be received, within 30 seconds
  604. timeoutSignal := make(chan struct{})
  605. go func() {
  606. timer := time.NewTimer(30 * time.Second)
  607. <-timer.C
  608. close(timeoutSignal)
  609. }()
  610. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel establish timeout exceeded")
  611. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  612. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  613. if runConfig.doTunneledWebRequest {
  614. // Test: tunneled web site fetch
  615. err = makeTunneledWebRequest(
  616. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  617. if err == nil {
  618. if expectTrafficFailure {
  619. t.Fatalf("unexpected tunneled web request success")
  620. }
  621. } else {
  622. if !expectTrafficFailure {
  623. t.Fatalf("tunneled web request failed: %s", err)
  624. }
  625. }
  626. }
  627. if runConfig.doTunneledNTPRequest {
  628. // Test: tunneled UDP packets
  629. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  630. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  631. if err == nil {
  632. if expectTrafficFailure {
  633. t.Fatalf("unexpected tunneled NTP request success")
  634. }
  635. } else {
  636. if !expectTrafficFailure {
  637. t.Fatalf("tunneled NTP request failed: %s", err)
  638. }
  639. }
  640. }
  641. // Test: await SLOK payload
  642. if !expectTrafficFailure {
  643. time.Sleep(1 * time.Second)
  644. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  645. numSLOKs := psiphon.CountSLOKs()
  646. if numSLOKs != expectedNumSLOKs {
  647. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  648. }
  649. }
  650. }
  651. func makeTunneledWebRequest(
  652. t *testing.T,
  653. localHTTPProxyPort int,
  654. requestURL, expectedResponseBody string) error {
  655. roundTripTimeout := 30 * time.Second
  656. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  657. if err != nil {
  658. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  659. }
  660. httpClient := &http.Client{
  661. Transport: &http.Transport{
  662. Proxy: http.ProxyURL(proxyUrl),
  663. },
  664. Timeout: roundTripTimeout,
  665. }
  666. response, err := httpClient.Get(requestURL)
  667. if err != nil {
  668. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  669. }
  670. body, err := ioutil.ReadAll(response.Body)
  671. if err != nil {
  672. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  673. }
  674. response.Body.Close()
  675. if string(body) != expectedResponseBody {
  676. return fmt.Errorf("unexpected proxied HTTP response")
  677. }
  678. return nil
  679. }
  680. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  681. timeout := 20 * time.Second
  682. var err error
  683. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  684. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  685. if err == nil {
  686. break
  687. }
  688. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  689. }
  690. return err
  691. }
  692. var nextUDPProxyPort = 7300
  693. func makeTunneledNTPRequestAttempt(
  694. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  695. nextUDPProxyPort++
  696. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  697. if err != nil {
  698. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  699. }
  700. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  701. // handles it, and then terminates.
  702. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  703. if waitGroup != nil {
  704. defer waitGroup.Done()
  705. }
  706. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  707. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  708. if err != nil {
  709. t.Logf("ListenUDP for %s failed: %s", destination, err)
  710. return
  711. }
  712. defer serverUDPConn.Close()
  713. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  714. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  715. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  716. buffer[udpgwPreambleSize:])
  717. if err != nil {
  718. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  719. return
  720. }
  721. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  722. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  723. if err != nil {
  724. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  725. return
  726. }
  727. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  728. if err != nil {
  729. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  730. return
  731. }
  732. defer socksTCPConn.Close()
  733. flags := uint8(0)
  734. if destinationPort == 53 {
  735. flags = udpgwProtocolFlagDNS
  736. }
  737. err = writeUdpgwPreamble(
  738. udpgwPreambleSize,
  739. flags,
  740. 0,
  741. destinationIP,
  742. destinationPort,
  743. uint16(packetSize),
  744. buffer)
  745. if err != nil {
  746. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  747. return
  748. }
  749. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  750. if err != nil {
  751. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  752. return
  753. }
  754. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  755. if err != nil {
  756. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  757. return
  758. }
  759. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  760. if err != nil {
  761. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  762. return
  763. }
  764. }
  765. // Tunneled DNS request
  766. waitGroup := new(sync.WaitGroup)
  767. waitGroup.Add(1)
  768. go localUDPProxy(
  769. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  770. 53,
  771. waitGroup)
  772. // TODO: properly synchronize with local UDP proxy startup
  773. time.Sleep(1 * time.Second)
  774. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  775. if err != nil {
  776. return fmt.Errorf("DialUDP failed: %s", err)
  777. }
  778. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  779. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  780. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  781. clientUDPConn.Close()
  782. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  783. err = errors.New("no address")
  784. }
  785. if err != nil {
  786. return fmt.Errorf("ResolveIP failed: %s", err)
  787. }
  788. waitGroup.Wait()
  789. // Tunneled NTP request
  790. waitGroup = new(sync.WaitGroup)
  791. waitGroup.Add(1)
  792. go localUDPProxy(
  793. addrs[0][len(addrs[0])-4:],
  794. 123,
  795. waitGroup)
  796. // TODO: properly synchronize with local UDP proxy startup
  797. time.Sleep(1 * time.Second)
  798. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  799. if err != nil {
  800. return fmt.Errorf("DialUDP failed: %s", err)
  801. }
  802. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  803. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  804. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  805. ntpData := make([]byte, 48)
  806. ntpData[0] = 3<<3 | 3
  807. _, err = clientUDPConn.Write(ntpData)
  808. if err != nil {
  809. clientUDPConn.Close()
  810. return fmt.Errorf("NTP Write failed: %s", err)
  811. }
  812. _, err = clientUDPConn.Read(ntpData)
  813. if err != nil {
  814. clientUDPConn.Close()
  815. return fmt.Errorf("NTP Read failed: %s", err)
  816. }
  817. clientUDPConn.Close()
  818. var sec, frac uint64
  819. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  820. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  821. nsec := sec * 1e9
  822. nsec += (frac * 1e9) >> 32
  823. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  824. now := time.Now()
  825. diff := ntpNow.Sub(now)
  826. if diff < 0 {
  827. diff = -diff
  828. }
  829. if diff > 1*time.Minute {
  830. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  831. }
  832. waitGroup.Wait()
  833. return nil
  834. }
  835. func pavePsinetDatabaseFile(
  836. t *testing.T, useDefaultSponsorID bool, psinetFilename string) (string, string) {
  837. sponsorID, _ := common.MakeSecureRandomStringHex(8)
  838. fakeDomain, _ := common.MakeSecureRandomStringHex(4)
  839. fakePath, _ := common.MakeSecureRandomStringHex(4)
  840. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  841. psinetJSONFormat := `
  842. {
  843. "default_sponsor_id" : "%s",
  844. "sponsors": {
  845. "%s": {
  846. "home_pages": {
  847. "None": [
  848. {
  849. "region": null,
  850. "url": "%s"
  851. }
  852. ]
  853. }
  854. }
  855. }
  856. }
  857. `
  858. defaultSponsorID := ""
  859. if useDefaultSponsorID {
  860. defaultSponsorID = sponsorID
  861. }
  862. psinetJSON := fmt.Sprintf(
  863. psinetJSONFormat, defaultSponsorID, sponsorID, expectedHomepageURL)
  864. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  865. if err != nil {
  866. t.Fatalf("error paving psinet database file: %s", err)
  867. }
  868. return sponsorID, expectedHomepageURL
  869. }
  870. func paveTrafficRulesFile(
  871. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  872. requireAuthorization, deny bool) {
  873. allowTCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  874. allowUDPPorts := "53, 123"
  875. if deny {
  876. allowTCPPorts = "0"
  877. allowUDPPorts = "0"
  878. }
  879. authorizationFilterFormat := `,
  880. "AuthorizedAccessTypes" : ["%s"]
  881. `
  882. authorizationFilter := ""
  883. if requireAuthorization {
  884. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  885. }
  886. trafficRulesJSONFormat := `
  887. {
  888. "DefaultRules" : {
  889. "RateLimits" : {
  890. "ReadBytesPerSecond": 16384,
  891. "WriteBytesPerSecond": 16384
  892. },
  893. "AllowTCPPorts" : [0],
  894. "AllowUDPPorts" : [0],
  895. "MeekRateLimiterHistorySize" : 10,
  896. "MeekRateLimiterThresholdSeconds" : 1,
  897. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  898. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  899. "MeekRateLimiterRegions" : []
  900. },
  901. "FilteredRules" : [
  902. {
  903. "Filter" : {
  904. "HandshakeParameters" : {
  905. "propagation_channel_id" : ["%s"]
  906. }%s
  907. },
  908. "Rules" : {
  909. "RateLimits" : {
  910. "ReadUnthrottledBytes": 132352,
  911. "WriteUnthrottledBytes": 132352
  912. },
  913. "AllowTCPPorts" : [%s],
  914. "AllowUDPPorts" : [%s]
  915. }
  916. }
  917. ]
  918. }
  919. `
  920. trafficRulesJSON := fmt.Sprintf(
  921. trafficRulesJSONFormat, propagationChannelID, authorizationFilter, allowTCPPorts, allowUDPPorts)
  922. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  923. if err != nil {
  924. t.Fatalf("error paving traffic rules file: %s", err)
  925. }
  926. }
  927. var expectedNumSLOKs = 3
  928. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  929. oslConfigJSONFormat := `
  930. {
  931. "Schemes" : [
  932. {
  933. "Epoch" : "%s",
  934. "Regions" : [],
  935. "PropagationChannelIDs" : ["%s"],
  936. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  937. "SeedSpecs" : [
  938. {
  939. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  940. "UpstreamSubnets" : ["0.0.0.0/0"],
  941. "Targets" :
  942. {
  943. "BytesRead" : 1,
  944. "BytesWritten" : 1,
  945. "PortForwardDurationNanoseconds" : 1
  946. }
  947. },
  948. {
  949. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  950. "UpstreamSubnets" : ["0.0.0.0/0"],
  951. "Targets" :
  952. {
  953. "BytesRead" : 1,
  954. "BytesWritten" : 1,
  955. "PortForwardDurationNanoseconds" : 1
  956. }
  957. }
  958. ],
  959. "SeedSpecThreshold" : 2,
  960. "SeedPeriodNanoseconds" : 2592000000000000,
  961. "SeedPeriodKeySplits": [
  962. {
  963. "Total": 2,
  964. "Threshold": 2
  965. }
  966. ]
  967. },
  968. {
  969. "Epoch" : "%s",
  970. "Regions" : [],
  971. "PropagationChannelIDs" : ["%s"],
  972. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  973. "SeedSpecs" : [
  974. {
  975. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  976. "UpstreamSubnets" : ["0.0.0.0/0"],
  977. "Targets" :
  978. {
  979. "BytesRead" : 1,
  980. "BytesWritten" : 1,
  981. "PortForwardDurationNanoseconds" : 1
  982. }
  983. }
  984. ],
  985. "SeedSpecThreshold" : 1,
  986. "SeedPeriodNanoseconds" : 2592000000000000,
  987. "SeedPeriodKeySplits": [
  988. {
  989. "Total": 1,
  990. "Threshold": 1
  991. }
  992. ]
  993. }
  994. ]
  995. }
  996. `
  997. propagationChannelID, _ := common.MakeSecureRandomStringHex(8)
  998. now := time.Now().UTC()
  999. epoch := now.Truncate(720 * time.Hour)
  1000. epochStr := epoch.Format(time.RFC3339Nano)
  1001. oslConfigJSON := fmt.Sprintf(
  1002. oslConfigJSONFormat,
  1003. epochStr, propagationChannelID,
  1004. epochStr, propagationChannelID)
  1005. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1006. if err != nil {
  1007. t.Fatalf("error paving osl config file: %s", err)
  1008. }
  1009. return propagationChannelID
  1010. }
  1011. func paveTacticsConfigFile(
  1012. t *testing.T, tacticsConfigFilename string,
  1013. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1014. tunnelProtocol string,
  1015. propagationChannelID string) {
  1016. // Setting LimitTunnelProtocols passively exercises the
  1017. // server-side LimitTunnelProtocols enforcement.
  1018. tacticsConfigJSONFormat := `
  1019. {
  1020. "RequestPublicKey" : "%s",
  1021. "RequestPrivateKey" : "%s",
  1022. "RequestObfuscatedKey" : "%s",
  1023. "EnforceServerSide" : true,
  1024. "DefaultTactics" : {
  1025. "TTL" : "60s",
  1026. "Probability" : 1.0,
  1027. "Parameters" : {
  1028. "LimitTunnelProtocols" : ["%s"]
  1029. }
  1030. },
  1031. "FilteredTactics" : [
  1032. {
  1033. "Filter" : {
  1034. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1035. "SpeedTestRTTMilliseconds" : {
  1036. "Aggregation" : "Median",
  1037. "AtLeast" : 1
  1038. }
  1039. },
  1040. "Tactics" : {
  1041. "Parameters" : {
  1042. "TunnelConnectTimeout" : "20s",
  1043. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000}
  1044. }
  1045. }
  1046. }
  1047. ]
  1048. }
  1049. `
  1050. tacticsConfigJSON := fmt.Sprintf(
  1051. tacticsConfigJSONFormat,
  1052. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1053. tunnelProtocol,
  1054. propagationChannelID)
  1055. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1056. if err != nil {
  1057. t.Fatalf("error paving tactics config file: %s", err)
  1058. }
  1059. }
  1060. func sendNotificationReceived(c chan<- struct{}) {
  1061. select {
  1062. case c <- *new(struct{}):
  1063. default:
  1064. }
  1065. }
  1066. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1067. select {
  1068. case <-c:
  1069. case <-timeoutSignal:
  1070. t.Fatalf(timeoutMessage)
  1071. }
  1072. }