server_test.go 47 KB

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