server_test.go 40 KB

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