server_test.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298
  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. "strings"
  34. "sync"
  35. "syscall"
  36. "testing"
  37. "time"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  48. "golang.org/x/net/proxy"
  49. )
  50. var serverIPAddress, testDataDirName string
  51. var mockWebServerURL, mockWebServerExpectedResponse string
  52. var mockWebServerPort = 8080
  53. func TestMain(m *testing.M) {
  54. flag.Parse()
  55. serverIPv4Address, serverIPv6Address, err := common.GetRoutableInterfaceIPAddresses()
  56. if err != nil {
  57. fmt.Printf("error getting server IP address: %s\n", err)
  58. os.Exit(1)
  59. }
  60. if serverIPv4Address != nil {
  61. serverIPAddress = serverIPv4Address.String()
  62. } else {
  63. serverIPAddress = serverIPv6Address.String()
  64. }
  65. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  66. if err != nil {
  67. fmt.Printf("TempDir failed: %s\n", err)
  68. os.Exit(1)
  69. }
  70. defer os.RemoveAll(testDataDirName)
  71. psiphon.SetEmitDiagnosticNotices(true, true)
  72. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  73. os.Exit(m.Run())
  74. }
  75. func runMockWebServer() (string, string) {
  76. responseBody := prng.HexString(100000)
  77. serveMux := http.NewServeMux()
  78. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  79. w.Write([]byte(responseBody))
  80. })
  81. webServerAddress := fmt.Sprintf("%s:%d", serverIPAddress, mockWebServerPort)
  82. server := &http.Server{
  83. Addr: webServerAddress,
  84. Handler: serveMux,
  85. }
  86. go func() {
  87. err := server.ListenAndServe()
  88. if err != nil {
  89. fmt.Printf("error running mock web server: %s\n", err)
  90. os.Exit(1)
  91. }
  92. }()
  93. // TODO: properly synchronize with web server readiness
  94. time.Sleep(1 * time.Second)
  95. return fmt.Sprintf("http://%s/", webServerAddress), responseBody
  96. }
  97. // Note: not testing fronted meek protocols, which client is
  98. // hard-wired to expect running on privileged ports 80 and 443.
  99. func TestSSH(t *testing.T) {
  100. runServer(t,
  101. &runServerConfig{
  102. tunnelProtocol: "SSH",
  103. enableSSHAPIRequests: true,
  104. doHotReload: false,
  105. doDefaultSponsorID: false,
  106. denyTrafficRules: false,
  107. requireAuthorization: true,
  108. omitAuthorization: false,
  109. doTunneledWebRequest: true,
  110. doTunneledNTPRequest: true,
  111. forceFragmenting: false,
  112. forceLivenessTest: false,
  113. doPruneServerEntries: false,
  114. doDanglingTCPConn: true,
  115. })
  116. }
  117. func TestOSSH(t *testing.T) {
  118. runServer(t,
  119. &runServerConfig{
  120. tunnelProtocol: "OSSH",
  121. enableSSHAPIRequests: true,
  122. doHotReload: false,
  123. doDefaultSponsorID: false,
  124. denyTrafficRules: false,
  125. requireAuthorization: true,
  126. omitAuthorization: false,
  127. doTunneledWebRequest: true,
  128. doTunneledNTPRequest: true,
  129. forceFragmenting: false,
  130. forceLivenessTest: false,
  131. doPruneServerEntries: false,
  132. doDanglingTCPConn: true,
  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. doPruneServerEntries: false,
  150. doDanglingTCPConn: true,
  151. })
  152. }
  153. func TestUnfrontedMeek(t *testing.T) {
  154. runServer(t,
  155. &runServerConfig{
  156. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  157. enableSSHAPIRequests: true,
  158. doHotReload: false,
  159. doDefaultSponsorID: false,
  160. denyTrafficRules: false,
  161. requireAuthorization: true,
  162. omitAuthorization: false,
  163. doTunneledWebRequest: true,
  164. doTunneledNTPRequest: true,
  165. forceFragmenting: false,
  166. forceLivenessTest: false,
  167. doPruneServerEntries: false,
  168. doDanglingTCPConn: true,
  169. })
  170. }
  171. func TestUnfrontedMeekHTTPS(t *testing.T) {
  172. runServer(t,
  173. &runServerConfig{
  174. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  175. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  176. enableSSHAPIRequests: true,
  177. doHotReload: false,
  178. doDefaultSponsorID: false,
  179. denyTrafficRules: false,
  180. requireAuthorization: true,
  181. omitAuthorization: false,
  182. doTunneledWebRequest: true,
  183. doTunneledNTPRequest: true,
  184. forceFragmenting: false,
  185. forceLivenessTest: false,
  186. doPruneServerEntries: false,
  187. doDanglingTCPConn: true,
  188. })
  189. }
  190. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  191. runServer(t,
  192. &runServerConfig{
  193. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  194. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  195. enableSSHAPIRequests: true,
  196. doHotReload: false,
  197. doDefaultSponsorID: false,
  198. denyTrafficRules: false,
  199. requireAuthorization: true,
  200. omitAuthorization: false,
  201. doTunneledWebRequest: true,
  202. doTunneledNTPRequest: true,
  203. forceFragmenting: false,
  204. forceLivenessTest: false,
  205. doPruneServerEntries: false,
  206. doDanglingTCPConn: true,
  207. })
  208. }
  209. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  210. runServer(t,
  211. &runServerConfig{
  212. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  213. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  214. enableSSHAPIRequests: true,
  215. doHotReload: false,
  216. doDefaultSponsorID: false,
  217. denyTrafficRules: false,
  218. requireAuthorization: true,
  219. omitAuthorization: false,
  220. doTunneledWebRequest: true,
  221. doTunneledNTPRequest: true,
  222. forceFragmenting: false,
  223. forceLivenessTest: false,
  224. doPruneServerEntries: false,
  225. doDanglingTCPConn: true,
  226. })
  227. }
  228. func TestUnfrontedMeekSessionTicketTLS13(t *testing.T) {
  229. runServer(t,
  230. &runServerConfig{
  231. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  232. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  233. enableSSHAPIRequests: true,
  234. doHotReload: false,
  235. doDefaultSponsorID: false,
  236. denyTrafficRules: false,
  237. requireAuthorization: true,
  238. omitAuthorization: false,
  239. doTunneledWebRequest: true,
  240. doTunneledNTPRequest: true,
  241. forceFragmenting: false,
  242. forceLivenessTest: false,
  243. doPruneServerEntries: false,
  244. doDanglingTCPConn: true,
  245. })
  246. }
  247. func TestQUICOSSH(t *testing.T) {
  248. if !quic.Enabled() {
  249. t.Skip("QUIC is not enabled")
  250. }
  251. runServer(t,
  252. &runServerConfig{
  253. tunnelProtocol: "QUIC-OSSH",
  254. enableSSHAPIRequests: true,
  255. doHotReload: false,
  256. doDefaultSponsorID: false,
  257. denyTrafficRules: false,
  258. requireAuthorization: true,
  259. omitAuthorization: false,
  260. doTunneledWebRequest: true,
  261. doTunneledNTPRequest: true,
  262. forceFragmenting: false,
  263. forceLivenessTest: false,
  264. doPruneServerEntries: false,
  265. doDanglingTCPConn: false,
  266. })
  267. }
  268. func TestMarionetteOSSH(t *testing.T) {
  269. if !marionette.Enabled() {
  270. t.Skip("Marionette is not enabled")
  271. }
  272. runServer(t,
  273. &runServerConfig{
  274. tunnelProtocol: "MARIONETTE-OSSH",
  275. enableSSHAPIRequests: true,
  276. doHotReload: false,
  277. doDefaultSponsorID: false,
  278. denyTrafficRules: false,
  279. requireAuthorization: true,
  280. omitAuthorization: false,
  281. doTunneledWebRequest: true,
  282. doTunneledNTPRequest: true,
  283. forceFragmenting: false,
  284. forceLivenessTest: false,
  285. doPruneServerEntries: false,
  286. doDanglingTCPConn: false,
  287. })
  288. }
  289. func TestWebTransportAPIRequests(t *testing.T) {
  290. runServer(t,
  291. &runServerConfig{
  292. tunnelProtocol: "OSSH",
  293. enableSSHAPIRequests: false,
  294. doHotReload: false,
  295. doDefaultSponsorID: false,
  296. denyTrafficRules: false,
  297. requireAuthorization: false,
  298. omitAuthorization: true,
  299. doTunneledWebRequest: true,
  300. doTunneledNTPRequest: true,
  301. forceFragmenting: false,
  302. forceLivenessTest: false,
  303. doPruneServerEntries: false,
  304. doDanglingTCPConn: false,
  305. })
  306. }
  307. func TestHotReload(t *testing.T) {
  308. runServer(t,
  309. &runServerConfig{
  310. tunnelProtocol: "OSSH",
  311. enableSSHAPIRequests: true,
  312. doHotReload: true,
  313. doDefaultSponsorID: false,
  314. denyTrafficRules: false,
  315. requireAuthorization: true,
  316. omitAuthorization: false,
  317. doTunneledWebRequest: true,
  318. doTunneledNTPRequest: true,
  319. forceFragmenting: false,
  320. forceLivenessTest: false,
  321. doPruneServerEntries: false,
  322. doDanglingTCPConn: false,
  323. })
  324. }
  325. func TestDefaultSponsorID(t *testing.T) {
  326. runServer(t,
  327. &runServerConfig{
  328. tunnelProtocol: "OSSH",
  329. enableSSHAPIRequests: true,
  330. doHotReload: true,
  331. doDefaultSponsorID: true,
  332. denyTrafficRules: false,
  333. requireAuthorization: true,
  334. omitAuthorization: false,
  335. doTunneledWebRequest: true,
  336. doTunneledNTPRequest: true,
  337. forceFragmenting: false,
  338. forceLivenessTest: false,
  339. doPruneServerEntries: false,
  340. doDanglingTCPConn: false,
  341. })
  342. }
  343. func TestDenyTrafficRules(t *testing.T) {
  344. runServer(t,
  345. &runServerConfig{
  346. tunnelProtocol: "OSSH",
  347. enableSSHAPIRequests: true,
  348. doHotReload: true,
  349. doDefaultSponsorID: false,
  350. denyTrafficRules: true,
  351. requireAuthorization: true,
  352. omitAuthorization: false,
  353. doTunneledWebRequest: true,
  354. doTunneledNTPRequest: true,
  355. forceFragmenting: false,
  356. forceLivenessTest: false,
  357. doPruneServerEntries: false,
  358. doDanglingTCPConn: false,
  359. })
  360. }
  361. func TestOmitAuthorization(t *testing.T) {
  362. runServer(t,
  363. &runServerConfig{
  364. tunnelProtocol: "OSSH",
  365. enableSSHAPIRequests: true,
  366. doHotReload: true,
  367. doDefaultSponsorID: false,
  368. denyTrafficRules: false,
  369. requireAuthorization: true,
  370. omitAuthorization: true,
  371. doTunneledWebRequest: true,
  372. doTunneledNTPRequest: true,
  373. forceFragmenting: false,
  374. forceLivenessTest: false,
  375. doPruneServerEntries: false,
  376. doDanglingTCPConn: false,
  377. })
  378. }
  379. func TestNoAuthorization(t *testing.T) {
  380. runServer(t,
  381. &runServerConfig{
  382. tunnelProtocol: "OSSH",
  383. enableSSHAPIRequests: true,
  384. doHotReload: true,
  385. doDefaultSponsorID: false,
  386. denyTrafficRules: false,
  387. requireAuthorization: false,
  388. omitAuthorization: true,
  389. doTunneledWebRequest: true,
  390. doTunneledNTPRequest: true,
  391. forceFragmenting: false,
  392. forceLivenessTest: false,
  393. doPruneServerEntries: false,
  394. doDanglingTCPConn: false,
  395. })
  396. }
  397. func TestUnusedAuthorization(t *testing.T) {
  398. runServer(t,
  399. &runServerConfig{
  400. tunnelProtocol: "OSSH",
  401. enableSSHAPIRequests: true,
  402. doHotReload: true,
  403. doDefaultSponsorID: false,
  404. denyTrafficRules: false,
  405. requireAuthorization: false,
  406. omitAuthorization: false,
  407. doTunneledWebRequest: true,
  408. doTunneledNTPRequest: true,
  409. forceFragmenting: false,
  410. forceLivenessTest: false,
  411. doPruneServerEntries: false,
  412. doDanglingTCPConn: false,
  413. })
  414. }
  415. func TestTCPOnlySLOK(t *testing.T) {
  416. runServer(t,
  417. &runServerConfig{
  418. tunnelProtocol: "OSSH",
  419. enableSSHAPIRequests: true,
  420. doHotReload: false,
  421. doDefaultSponsorID: false,
  422. denyTrafficRules: false,
  423. requireAuthorization: true,
  424. omitAuthorization: false,
  425. doTunneledWebRequest: true,
  426. doTunneledNTPRequest: false,
  427. forceFragmenting: false,
  428. forceLivenessTest: false,
  429. doPruneServerEntries: false,
  430. doDanglingTCPConn: false,
  431. })
  432. }
  433. func TestUDPOnlySLOK(t *testing.T) {
  434. runServer(t,
  435. &runServerConfig{
  436. tunnelProtocol: "OSSH",
  437. enableSSHAPIRequests: true,
  438. doHotReload: false,
  439. doDefaultSponsorID: false,
  440. denyTrafficRules: false,
  441. requireAuthorization: true,
  442. omitAuthorization: false,
  443. doTunneledWebRequest: false,
  444. doTunneledNTPRequest: true,
  445. forceFragmenting: false,
  446. forceLivenessTest: false,
  447. doPruneServerEntries: false,
  448. doDanglingTCPConn: false,
  449. })
  450. }
  451. func TestLivenessTest(t *testing.T) {
  452. runServer(t,
  453. &runServerConfig{
  454. tunnelProtocol: "OSSH",
  455. enableSSHAPIRequests: true,
  456. doHotReload: false,
  457. doDefaultSponsorID: false,
  458. denyTrafficRules: false,
  459. requireAuthorization: true,
  460. omitAuthorization: false,
  461. doTunneledWebRequest: true,
  462. doTunneledNTPRequest: true,
  463. forceFragmenting: false,
  464. forceLivenessTest: true,
  465. doPruneServerEntries: false,
  466. doDanglingTCPConn: false,
  467. })
  468. }
  469. func TestPruneServerEntries(t *testing.T) {
  470. runServer(t,
  471. &runServerConfig{
  472. tunnelProtocol: "OSSH",
  473. enableSSHAPIRequests: true,
  474. doHotReload: false,
  475. doDefaultSponsorID: false,
  476. denyTrafficRules: false,
  477. requireAuthorization: true,
  478. omitAuthorization: false,
  479. doTunneledWebRequest: true,
  480. doTunneledNTPRequest: true,
  481. forceFragmenting: false,
  482. forceLivenessTest: true,
  483. doPruneServerEntries: true,
  484. doDanglingTCPConn: false,
  485. })
  486. }
  487. type runServerConfig struct {
  488. tunnelProtocol string
  489. tlsProfile string
  490. enableSSHAPIRequests bool
  491. doHotReload bool
  492. doDefaultSponsorID bool
  493. denyTrafficRules bool
  494. requireAuthorization bool
  495. omitAuthorization bool
  496. doTunneledWebRequest bool
  497. doTunneledNTPRequest bool
  498. forceFragmenting bool
  499. forceLivenessTest bool
  500. doPruneServerEntries bool
  501. doDanglingTCPConn bool
  502. }
  503. var (
  504. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  505. testUserAgents = []string{"ua1", "ua2", "ua3"}
  506. testNetworkType = "WIFI"
  507. testAppID = "com.test.app"
  508. )
  509. func runServer(t *testing.T, runConfig *runServerConfig) {
  510. // configure authorized access
  511. accessType := "test-access-type"
  512. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  513. if err != nil {
  514. t.Fatalf("error creating access control key pair: %s", err)
  515. }
  516. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  517. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  518. }
  519. var authorizationID [32]byte
  520. clientAuthorization, _, err := accesscontrol.IssueAuthorization(
  521. accessControlSigningKey,
  522. authorizationID[:],
  523. time.Now().Add(1*time.Hour))
  524. if err != nil {
  525. t.Fatalf("error issuing authorization: %s", err)
  526. }
  527. // Enable tactics when the test protocol is meek. Both the client and the
  528. // server will be configured to support tactics. The client config will be
  529. // set with a nonfunctional config so that the tactics request must
  530. // succeed, overriding the nonfunctional values, for the tunnel to
  531. // establish.
  532. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol)
  533. doServerTactics := doClientTactics || runConfig.forceFragmenting
  534. // All servers require a tactics config with valid keys.
  535. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  536. tactics.GenerateKeys()
  537. if err != nil {
  538. t.Fatalf("error generating tactics keys: %s", err)
  539. }
  540. livenessTestSize := 0
  541. if doClientTactics || runConfig.forceLivenessTest {
  542. livenessTestSize = 1048576
  543. }
  544. // create a server
  545. psiphonServerIPAddress := serverIPAddress
  546. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) ||
  547. protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  548. // Workaround for macOS firewall.
  549. psiphonServerIPAddress = "127.0.0.1"
  550. }
  551. psiphonServerPort := 4000
  552. generateConfigParams := &GenerateConfigParams{
  553. ServerIPAddress: psiphonServerIPAddress,
  554. EnableSSHAPIRequests: runConfig.enableSSHAPIRequests,
  555. WebServerPort: 8000,
  556. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: psiphonServerPort},
  557. }
  558. if protocol.TunnelProtocolUsesMarionette(runConfig.tunnelProtocol) {
  559. generateConfigParams.TunnelProtocolPorts[runConfig.tunnelProtocol] = 0
  560. generateConfigParams.MarionetteFormat = "http_simple_nonblocking"
  561. }
  562. if doServerTactics {
  563. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  564. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  565. }
  566. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  567. if err != nil {
  568. t.Fatalf("error generating server config: %s", err)
  569. }
  570. // customize server config
  571. // Initialize prune server entry test cases and associated data to pave into psinet.
  572. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  573. initializePruneServerEntriesTest(t, runConfig)
  574. // Pave psinet with random values to test handshake homepages.
  575. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  576. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  577. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  578. // Pave OSL config for SLOK testing
  579. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  580. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  581. // Pave traffic rules file which exercises handshake parameter filtering. Client
  582. // must handshake with specified sponsor ID in order to allow ports for tunneled
  583. // requests.
  584. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  585. paveTrafficRulesFile(
  586. t, trafficRulesFilename, propagationChannelID, accessType,
  587. runConfig.requireAuthorization, runConfig.denyTrafficRules, livenessTestSize)
  588. var tacticsConfigFilename string
  589. // Only pave the tactics config when tactics are required. This exercises the
  590. // case where the tactics config is omitted.
  591. if doServerTactics {
  592. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  593. paveTacticsConfigFile(
  594. t, tacticsConfigFilename,
  595. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  596. runConfig.tunnelProtocol,
  597. propagationChannelID,
  598. livenessTestSize)
  599. }
  600. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  601. paveBlocklistFile(t, blocklistFilename)
  602. var serverConfig map[string]interface{}
  603. json.Unmarshal(serverConfigJSON, &serverConfig)
  604. serverConfig["GeoIPDatabaseFilename"] = ""
  605. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  606. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  607. serverConfig["OSLConfigFilename"] = oslConfigFilename
  608. if doServerTactics {
  609. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  610. }
  611. serverConfig["BlocklistFilename"] = blocklistFilename
  612. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  613. serverConfig["LogLevel"] = "debug"
  614. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  615. // Set this parameter so at least the semaphore functions are called.
  616. // TODO: test that the concurrency limit is correctly enforced.
  617. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  618. // Exercise this option.
  619. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  620. serverConfigJSON, _ = json.Marshal(serverConfig)
  621. serverConnectedLog := make(chan map[string]interface{}, 1)
  622. serverTunnelLog := make(chan map[string]interface{}, 1)
  623. setLogCallback(func(log []byte) {
  624. logFields := make(map[string]interface{})
  625. err := json.Unmarshal(log, &logFields)
  626. if err != nil {
  627. return
  628. }
  629. if logFields["event_name"] == nil {
  630. return
  631. }
  632. switch logFields["event_name"].(string) {
  633. case "connected":
  634. select {
  635. case serverConnectedLog <- logFields:
  636. default:
  637. }
  638. case "server_tunnel":
  639. select {
  640. case serverTunnelLog <- logFields:
  641. default:
  642. }
  643. }
  644. })
  645. // run server
  646. serverWaitGroup := new(sync.WaitGroup)
  647. serverWaitGroup.Add(1)
  648. go func() {
  649. defer serverWaitGroup.Done()
  650. err := RunServices(serverConfigJSON)
  651. if err != nil {
  652. // TODO: wrong goroutine for t.FatalNow()
  653. t.Errorf("error running server: %s", err)
  654. }
  655. }()
  656. stopServer := func() {
  657. // Test: orderly server shutdown
  658. p, _ := os.FindProcess(os.Getpid())
  659. p.Signal(os.Interrupt)
  660. shutdownTimeout := time.NewTimer(5 * time.Second)
  661. shutdownOk := make(chan struct{}, 1)
  662. go func() {
  663. serverWaitGroup.Wait()
  664. shutdownOk <- struct{}{}
  665. }()
  666. select {
  667. case <-shutdownOk:
  668. case <-shutdownTimeout.C:
  669. t.Errorf("server shutdown timeout exceeded")
  670. }
  671. }
  672. // Stop server on early exits due to failure.
  673. defer func() {
  674. if stopServer != nil {
  675. stopServer()
  676. }
  677. }()
  678. // TODO: monitor logs for more robust wait-until-loaded. For example,
  679. // especially with the race detector on, QUIC-OSSH tests can fail as the
  680. // client sends its initial packet before the server is ready.
  681. time.Sleep(1 * time.Second)
  682. // Test: hot reload (of psinet and traffic rules)
  683. if runConfig.doHotReload {
  684. // Pave new config files with different random values.
  685. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  686. t, runConfig.doDefaultSponsorID, psinetFilename, psinetValidServerEntryTags)
  687. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  688. paveTrafficRulesFile(
  689. t, trafficRulesFilename, propagationChannelID, accessType,
  690. runConfig.requireAuthorization, runConfig.denyTrafficRules,
  691. livenessTestSize)
  692. p, _ := os.FindProcess(os.Getpid())
  693. p.Signal(syscall.SIGUSR1)
  694. // TODO: monitor logs for more robust wait-until-reloaded
  695. time.Sleep(1 * time.Second)
  696. // After reloading psinet, the new sponsorID/expectedHomepageURL
  697. // should be active, as tested in the client "Homepage" notice
  698. // handler below.
  699. }
  700. // Exercise server_load logging
  701. p, _ := os.FindProcess(os.Getpid())
  702. p.Signal(syscall.SIGUSR2)
  703. // configure client
  704. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  705. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  706. // TODO: currently, TargetServerEntry only works with one tunnel
  707. numTunnels := 1
  708. localSOCKSProxyPort := 1081
  709. localHTTPProxyPort := 8081
  710. // Use a distinct suffix for network ID for each test run to
  711. // ensure tactics from different runs don't apply; this is
  712. // a workaround for the singleton datastore.
  713. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "WIFI-%s"`, time.Now().String())
  714. jsonLimitTLSProfiles := ""
  715. if runConfig.tlsProfile != "" {
  716. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  717. }
  718. clientConfigJSON := fmt.Sprintf(`
  719. {
  720. "ClientPlatform" : "Android_10_%s",
  721. "ClientVersion" : "0",
  722. "SponsorId" : "0",
  723. "PropagationChannelId" : "0",
  724. "TunnelWholeDevice" : 1,
  725. "DeviceRegion" : "US",
  726. "DisableRemoteServerListFetcher" : true,
  727. "EstablishTunnelPausePeriodSeconds" : 1,
  728. "ConnectionWorkerPoolSize" : %d,
  729. "LimitTunnelProtocols" : ["%s"]
  730. %s
  731. %s
  732. }`, testAppID, numTunnels, runConfig.tunnelProtocol, jsonLimitTLSProfiles, jsonNetworkID)
  733. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  734. if err != nil {
  735. t.Fatalf("error processing configuration file: %s", err)
  736. }
  737. clientConfig.DataRootDirectory = testDataDirName
  738. if !runConfig.doDefaultSponsorID {
  739. clientConfig.SponsorId = sponsorID
  740. }
  741. clientConfig.PropagationChannelId = propagationChannelID
  742. clientConfig.TunnelPoolSize = numTunnels
  743. clientConfig.TargetServerEntry = string(encodedServerEntry)
  744. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  745. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  746. clientConfig.EmitSLOKs = true
  747. clientConfig.EmitServerAlerts = true
  748. if !runConfig.omitAuthorization {
  749. clientConfig.Authorizations = []string{clientAuthorization}
  750. }
  751. err = clientConfig.Commit(false)
  752. if err != nil {
  753. t.Fatalf("error committing configuration file: %s", err)
  754. }
  755. if doClientTactics {
  756. // Configure nonfunctional values that must be overridden by tactics.
  757. applyParameters := make(map[string]interface{})
  758. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  759. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  760. err = clientConfig.SetClientParameters("", true, applyParameters)
  761. if err != nil {
  762. t.Fatalf("SetClientParameters failed: %s", err)
  763. }
  764. } else {
  765. // Directly apply same parameters that would've come from tactics.
  766. applyParameters := make(map[string]interface{})
  767. if runConfig.forceFragmenting {
  768. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  769. applyParameters[parameters.FragmentorProbability] = 1.0
  770. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  771. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  772. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  773. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  774. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  775. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  776. }
  777. if runConfig.forceLivenessTest {
  778. applyParameters[parameters.LivenessTestMinUpstreamBytes] = livenessTestSize
  779. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = livenessTestSize
  780. applyParameters[parameters.LivenessTestMinDownstreamBytes] = livenessTestSize
  781. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = livenessTestSize
  782. }
  783. if runConfig.doPruneServerEntries {
  784. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Millisecond
  785. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Millisecond
  786. }
  787. err = clientConfig.SetClientParameters("", true, applyParameters)
  788. if err != nil {
  789. t.Fatalf("SetClientParameters failed: %s", err)
  790. }
  791. }
  792. // connect to server with client
  793. err = psiphon.OpenDataStore(clientConfig)
  794. if err != nil {
  795. t.Fatalf("error initializing client datastore: %s", err)
  796. }
  797. defer psiphon.CloseDataStore()
  798. // Clear SLOKs from previous test runs.
  799. psiphon.DeleteSLOKs()
  800. // Store prune server entry test server entries and failed tunnel records.
  801. storePruneServerEntriesTest(
  802. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  803. controller, err := psiphon.NewController(clientConfig)
  804. if err != nil {
  805. t.Fatalf("error creating client controller: %s", err)
  806. }
  807. connectedServer := make(chan struct{}, 1)
  808. tunnelsEstablished := make(chan struct{}, 1)
  809. homepageReceived := make(chan struct{}, 1)
  810. slokSeeded := make(chan struct{}, 1)
  811. numPruneNotices := 0
  812. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  813. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  814. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  815. func(notice []byte) {
  816. //fmt.Printf("%s\n", string(notice))
  817. noticeType, payload, err := psiphon.GetNotice(notice)
  818. if err != nil {
  819. return
  820. }
  821. switch noticeType {
  822. case "ConnectedServer":
  823. sendNotificationReceived(connectedServer)
  824. case "Tunnels":
  825. count := int(payload["count"].(float64))
  826. if count >= numTunnels {
  827. sendNotificationReceived(tunnelsEstablished)
  828. }
  829. case "Homepage":
  830. homepageURL := payload["url"].(string)
  831. if homepageURL != expectedHomepageURL {
  832. // TODO: wrong goroutine for t.FatalNow()
  833. t.Errorf("unexpected homepage: %s", homepageURL)
  834. }
  835. sendNotificationReceived(homepageReceived)
  836. case "SLOKSeeded":
  837. sendNotificationReceived(slokSeeded)
  838. case "PruneServerEntry":
  839. numPruneNotices += 1
  840. if numPruneNotices == expectedNumPruneNotices {
  841. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  842. }
  843. case "ServerAlert":
  844. reason := payload["reason"].(string)
  845. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC {
  846. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  847. }
  848. }
  849. }))
  850. ctx, cancelFunc := context.WithCancel(context.Background())
  851. controllerWaitGroup := new(sync.WaitGroup)
  852. controllerWaitGroup.Add(1)
  853. go func() {
  854. defer controllerWaitGroup.Done()
  855. controller.Run(ctx)
  856. }()
  857. stopClient := func() {
  858. cancelFunc()
  859. shutdownTimeout := time.NewTimer(20 * time.Second)
  860. shutdownOk := make(chan struct{}, 1)
  861. go func() {
  862. controllerWaitGroup.Wait()
  863. shutdownOk <- struct{}{}
  864. }()
  865. select {
  866. case <-shutdownOk:
  867. case <-shutdownTimeout.C:
  868. t.Errorf("controller shutdown timeout exceeded")
  869. }
  870. }
  871. // Stop client on early exits due to failure.
  872. defer func() {
  873. if stopClient != nil {
  874. stopClient()
  875. }
  876. }()
  877. // Test: tunnels must be established, and correct homepage
  878. // must be received, within 30 seconds
  879. timeoutSignal := make(chan struct{})
  880. go func() {
  881. timer := time.NewTimer(30 * time.Second)
  882. <-timer.C
  883. close(timeoutSignal)
  884. }()
  885. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  886. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  887. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  888. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  889. if runConfig.doTunneledWebRequest {
  890. // Test: tunneled web site fetch
  891. err = makeTunneledWebRequest(
  892. t, localHTTPProxyPort, mockWebServerURL, mockWebServerExpectedResponse)
  893. if err == nil {
  894. if expectTrafficFailure {
  895. t.Fatalf("unexpected tunneled web request success")
  896. }
  897. } else {
  898. if !expectTrafficFailure {
  899. t.Fatalf("tunneled web request failed: %s", err)
  900. }
  901. }
  902. }
  903. if runConfig.doTunneledNTPRequest {
  904. // Test: tunneled UDP packets
  905. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  906. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  907. if err == nil {
  908. if expectTrafficFailure {
  909. t.Fatalf("unexpected tunneled NTP request success")
  910. }
  911. } else {
  912. if !expectTrafficFailure {
  913. t.Fatalf("tunneled NTP request failed: %s", err)
  914. }
  915. }
  916. }
  917. // Test: await SLOK payload or server alert notice
  918. time.Sleep(1 * time.Second)
  919. if !expectTrafficFailure {
  920. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  921. numSLOKs := psiphon.CountSLOKs()
  922. if numSLOKs != expectedNumSLOKs {
  923. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  924. }
  925. } else {
  926. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  927. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  928. }
  929. // Test: await expected prune server entry notices
  930. //
  931. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  932. if expectedNumPruneNotices > 0 {
  933. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  934. }
  935. if runConfig.doDanglingTCPConn {
  936. // Test: client that has established TCP connection but not completed
  937. // any handshakes must not block/delay server shutdown
  938. danglingConn, err := net.Dial(
  939. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  940. if err != nil {
  941. t.Fatalf("TCP dial failed: %s", err)
  942. }
  943. defer danglingConn.Close()
  944. }
  945. // Shutdown to ensure logs/notices are flushed
  946. stopClient()
  947. stopClient = nil
  948. stopServer()
  949. stopServer = nil
  950. // Test: all expected server logs were emitted
  951. // TODO: stops should be fully synchronous, but, intermittently,
  952. // server_tunnel fails to appear ("missing server tunnel log")
  953. // without this delay.
  954. time.Sleep(100 * time.Millisecond)
  955. select {
  956. case logFields := <-serverConnectedLog:
  957. err := checkExpectedLogFields(runConfig, false, false, logFields)
  958. if err != nil {
  959. t.Fatalf("invalid server connected log fields: %s", err)
  960. }
  961. default:
  962. t.Fatalf("missing server connected log")
  963. }
  964. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics
  965. expectServerBPFField := ServerBPFEnabled() && doServerTactics
  966. select {
  967. case logFields := <-serverTunnelLog:
  968. err := checkExpectedLogFields(runConfig, expectClientBPFField, expectServerBPFField, logFields)
  969. if err != nil {
  970. t.Fatalf("invalid server tunnel log fields: %s", err)
  971. }
  972. default:
  973. t.Fatalf("missing server tunnel log")
  974. }
  975. // Check that datastore had retained/pruned server entries as expected.
  976. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  977. }
  978. func checkExpectedLogFields(
  979. runConfig *runServerConfig,
  980. expectClientBPFField bool,
  981. expectServerBPFField bool,
  982. fields map[string]interface{}) error {
  983. // Limitations:
  984. //
  985. // - client_build_rev not set in test build (see common/buildinfo.go)
  986. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  987. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  988. for _, name := range []string{
  989. "session_id",
  990. "last_connected",
  991. "establishment_duration",
  992. "propagation_channel_id",
  993. "sponsor_id",
  994. "client_platform",
  995. "relay_protocol",
  996. "tunnel_whole_device",
  997. "device_region",
  998. "ssh_client_version",
  999. "server_entry_region",
  1000. "server_entry_source",
  1001. "server_entry_timestamp",
  1002. "dial_port_number",
  1003. "is_replay",
  1004. "dial_duration",
  1005. "candidate_number",
  1006. "established_tunnels_count",
  1007. "network_latency_multiplier",
  1008. "network_type",
  1009. "client_app_id",
  1010. } {
  1011. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1012. return fmt.Errorf("missing expected field '%s'", name)
  1013. }
  1014. }
  1015. if fields["relay_protocol"].(string) != runConfig.tunnelProtocol {
  1016. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  1017. }
  1018. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  1019. return fmt.Errorf("unexpected relay_protocol '%s'", fields["ssh_client_version"])
  1020. }
  1021. if protocol.TunnelProtocolUsesObfuscatedSSH(runConfig.tunnelProtocol) {
  1022. for _, name := range []string{
  1023. "padding",
  1024. "pad_response",
  1025. } {
  1026. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1027. return fmt.Errorf("missing expected field '%s'", name)
  1028. }
  1029. }
  1030. }
  1031. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1032. for _, name := range []string{
  1033. "user_agent",
  1034. "meek_transformed_host_name",
  1035. "meek_cookie_size",
  1036. "meek_limit_request",
  1037. tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME,
  1038. } {
  1039. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1040. return fmt.Errorf("missing expected field '%s'", name)
  1041. }
  1042. }
  1043. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  1044. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  1045. }
  1046. }
  1047. if protocol.TunnelProtocolUsesMeekHTTP(runConfig.tunnelProtocol) {
  1048. for _, name := range []string{
  1049. "meek_host_header",
  1050. } {
  1051. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1052. return fmt.Errorf("missing expected field '%s'", name)
  1053. }
  1054. }
  1055. for _, name := range []string{
  1056. "meek_dial_ip_address",
  1057. "meek_resolved_ip_address",
  1058. } {
  1059. if fields[name] != nil {
  1060. return fmt.Errorf("unexpected field '%s'", name)
  1061. }
  1062. }
  1063. }
  1064. if protocol.TunnelProtocolUsesMeekHTTPS(runConfig.tunnelProtocol) {
  1065. for _, name := range []string{
  1066. "tls_profile",
  1067. "tls_version",
  1068. "meek_sni_server_name",
  1069. } {
  1070. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1071. return fmt.Errorf("missing expected field '%s'", name)
  1072. }
  1073. }
  1074. for _, name := range []string{
  1075. "meek_dial_ip_address",
  1076. "meek_resolved_ip_address",
  1077. "meek_host_header",
  1078. } {
  1079. if fields[name] != nil {
  1080. return fmt.Errorf("unexpected field '%s'", name)
  1081. }
  1082. }
  1083. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  1084. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  1085. }
  1086. tlsVersion := fields["tls_version"].(string)
  1087. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  1088. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  1089. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  1090. }
  1091. }
  1092. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) {
  1093. for _, name := range []string{
  1094. "quic_version",
  1095. "quic_dial_sni_address",
  1096. } {
  1097. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1098. return fmt.Errorf("missing expected field '%s'", name)
  1099. }
  1100. }
  1101. if !common.Contains(protocol.SupportedQUICVersions, fields["quic_version"].(string)) {
  1102. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  1103. }
  1104. }
  1105. if runConfig.forceFragmenting {
  1106. for _, name := range []string{
  1107. "upstream_bytes_fragmented",
  1108. "upstream_min_bytes_written",
  1109. "upstream_max_bytes_written",
  1110. "upstream_min_delayed",
  1111. "upstream_max_delayed",
  1112. } {
  1113. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  1114. return fmt.Errorf("missing expected field '%s'", name)
  1115. }
  1116. }
  1117. }
  1118. if expectClientBPFField {
  1119. name := "client_bpf"
  1120. if fields[name] == nil {
  1121. return fmt.Errorf("missing expected field '%s'", name)
  1122. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  1123. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1124. }
  1125. }
  1126. if expectServerBPFField {
  1127. name := "server_bpf"
  1128. if fields[name] == nil {
  1129. return fmt.Errorf("missing expected field '%s'", name)
  1130. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  1131. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  1132. }
  1133. }
  1134. if fields["network_type"].(string) != testNetworkType {
  1135. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  1136. }
  1137. if fields["client_app_id"].(string) != testAppID {
  1138. return fmt.Errorf("unexpected client_app_id '%s'", fields["client_app_id"])
  1139. }
  1140. return nil
  1141. }
  1142. func makeTunneledWebRequest(
  1143. t *testing.T,
  1144. localHTTPProxyPort int,
  1145. requestURL, expectedResponseBody string) error {
  1146. roundTripTimeout := 30 * time.Second
  1147. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  1148. if err != nil {
  1149. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  1150. }
  1151. httpClient := &http.Client{
  1152. Transport: &http.Transport{
  1153. Proxy: http.ProxyURL(proxyUrl),
  1154. },
  1155. Timeout: roundTripTimeout,
  1156. }
  1157. response, err := httpClient.Get(requestURL)
  1158. if err != nil {
  1159. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  1160. }
  1161. body, err := ioutil.ReadAll(response.Body)
  1162. if err != nil {
  1163. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  1164. }
  1165. response.Body.Close()
  1166. if string(body) != expectedResponseBody {
  1167. return fmt.Errorf("unexpected proxied HTTP response")
  1168. }
  1169. return nil
  1170. }
  1171. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1172. timeout := 20 * time.Second
  1173. var err error
  1174. for _, testHostname := range []string{"time.google.com", "time.nist.gov", "pool.ntp.org"} {
  1175. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  1176. if err == nil {
  1177. break
  1178. }
  1179. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  1180. }
  1181. return err
  1182. }
  1183. var nextUDPProxyPort = 7300
  1184. func makeTunneledNTPRequestAttempt(
  1185. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  1186. nextUDPProxyPort++
  1187. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  1188. if err != nil {
  1189. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  1190. }
  1191. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  1192. // handles it, and then terminates.
  1193. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  1194. if waitGroup != nil {
  1195. defer waitGroup.Done()
  1196. }
  1197. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  1198. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  1199. if err != nil {
  1200. t.Logf("ListenUDP for %s failed: %s", destination, err)
  1201. return
  1202. }
  1203. defer serverUDPConn.Close()
  1204. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  1205. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  1206. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  1207. buffer[udpgwPreambleSize:])
  1208. if err != nil {
  1209. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  1210. return
  1211. }
  1212. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  1213. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  1214. if err != nil {
  1215. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  1216. return
  1217. }
  1218. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  1219. if err != nil {
  1220. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  1221. return
  1222. }
  1223. defer socksTCPConn.Close()
  1224. flags := uint8(0)
  1225. if destinationPort == 53 {
  1226. flags = udpgwProtocolFlagDNS
  1227. }
  1228. err = writeUdpgwPreamble(
  1229. udpgwPreambleSize,
  1230. flags,
  1231. 0,
  1232. destinationIP,
  1233. destinationPort,
  1234. uint16(packetSize),
  1235. buffer)
  1236. if err != nil {
  1237. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  1238. return
  1239. }
  1240. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  1241. if err != nil {
  1242. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  1243. return
  1244. }
  1245. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  1246. if err != nil {
  1247. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  1248. return
  1249. }
  1250. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  1251. if err != nil {
  1252. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  1253. return
  1254. }
  1255. }
  1256. // Tunneled DNS request
  1257. waitGroup := new(sync.WaitGroup)
  1258. waitGroup.Add(1)
  1259. go localUDPProxy(
  1260. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  1261. 53,
  1262. waitGroup)
  1263. // TODO: properly synchronize with local UDP proxy startup
  1264. time.Sleep(1 * time.Second)
  1265. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  1266. if err != nil {
  1267. return fmt.Errorf("DialUDP failed: %s", err)
  1268. }
  1269. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1270. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1271. addrs, _, err := psiphon.ResolveIP(testHostname, clientUDPConn)
  1272. clientUDPConn.Close()
  1273. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  1274. err = errors.New("no address")
  1275. }
  1276. if err != nil {
  1277. return fmt.Errorf("ResolveIP failed: %s", err)
  1278. }
  1279. waitGroup.Wait()
  1280. // Tunneled NTP request
  1281. waitGroup = new(sync.WaitGroup)
  1282. waitGroup.Add(1)
  1283. go localUDPProxy(
  1284. addrs[0][len(addrs[0])-4:],
  1285. 123,
  1286. waitGroup)
  1287. // TODO: properly synchronize with local UDP proxy startup
  1288. time.Sleep(1 * time.Second)
  1289. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  1290. if err != nil {
  1291. return fmt.Errorf("DialUDP failed: %s", err)
  1292. }
  1293. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  1294. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  1295. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  1296. ntpData := make([]byte, 48)
  1297. ntpData[0] = 3<<3 | 3
  1298. _, err = clientUDPConn.Write(ntpData)
  1299. if err != nil {
  1300. clientUDPConn.Close()
  1301. return fmt.Errorf("NTP Write failed: %s", err)
  1302. }
  1303. _, err = clientUDPConn.Read(ntpData)
  1304. if err != nil {
  1305. clientUDPConn.Close()
  1306. return fmt.Errorf("NTP Read failed: %s", err)
  1307. }
  1308. clientUDPConn.Close()
  1309. var sec, frac uint64
  1310. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  1311. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  1312. nsec := sec * 1e9
  1313. nsec += (frac * 1e9) >> 32
  1314. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  1315. now := time.Now()
  1316. diff := ntpNow.Sub(now)
  1317. if diff < 0 {
  1318. diff = -diff
  1319. }
  1320. if diff > 1*time.Minute {
  1321. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  1322. }
  1323. waitGroup.Wait()
  1324. return nil
  1325. }
  1326. func pavePsinetDatabaseFile(
  1327. t *testing.T,
  1328. useDefaultSponsorID bool,
  1329. psinetFilename string,
  1330. validServerEntryTags []string) (string, string) {
  1331. sponsorID := prng.HexString(8)
  1332. defaultSponsorID := ""
  1333. if useDefaultSponsorID {
  1334. defaultSponsorID = sponsorID
  1335. }
  1336. fakeDomain := prng.HexString(4)
  1337. fakePath := prng.HexString(4)
  1338. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  1339. psinetJSONFormat := `
  1340. {
  1341. "default_sponsor_id" : "%s",
  1342. "sponsors": {
  1343. "%s": {
  1344. "home_pages": {
  1345. "None": [
  1346. {
  1347. "region": null,
  1348. "url": "%s"
  1349. }
  1350. ]
  1351. }
  1352. }
  1353. },
  1354. "valid_server_entry_tags" : {
  1355. %s
  1356. }
  1357. }
  1358. `
  1359. validServerEntryTagsJSON := ""
  1360. for _, serverEntryTag := range validServerEntryTags {
  1361. if len(validServerEntryTagsJSON) > 0 {
  1362. validServerEntryTagsJSON += ", "
  1363. }
  1364. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  1365. }
  1366. psinetJSON := fmt.Sprintf(
  1367. psinetJSONFormat,
  1368. defaultSponsorID,
  1369. sponsorID,
  1370. expectedHomepageURL,
  1371. validServerEntryTagsJSON)
  1372. err := ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  1373. if err != nil {
  1374. t.Fatalf("error paving psinet database file: %s", err)
  1375. }
  1376. return sponsorID, expectedHomepageURL
  1377. }
  1378. func paveTrafficRulesFile(
  1379. t *testing.T, trafficRulesFilename, propagationChannelID, accessType string,
  1380. requireAuthorization, deny bool,
  1381. livenessTestSize int) {
  1382. // Test both default and fast lookups
  1383. if intLookupThreshold != 10 {
  1384. t.Fatalf("unexpected intLookupThreshold")
  1385. }
  1386. TCPPorts := fmt.Sprintf("%d", mockWebServerPort)
  1387. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  1388. allowTCPPorts := TCPPorts
  1389. allowUDPPorts := UDPPorts
  1390. disallowTCPPorts := "0"
  1391. disallowUDPPorts := "0"
  1392. if deny {
  1393. allowTCPPorts = "0"
  1394. allowUDPPorts = "0"
  1395. disallowTCPPorts = TCPPorts
  1396. disallowUDPPorts = UDPPorts
  1397. }
  1398. authorizationFilterFormat := `,
  1399. "AuthorizedAccessTypes" : ["%s"]
  1400. `
  1401. authorizationFilter := ""
  1402. if requireAuthorization {
  1403. authorizationFilter = fmt.Sprintf(authorizationFilterFormat, accessType)
  1404. }
  1405. // Supports two traffic rule test cases:
  1406. //
  1407. // 1. no ports are allowed until after the filtered rule is applied
  1408. // 2. no required ports are allowed (deny = true)
  1409. trafficRulesJSONFormat := `
  1410. {
  1411. "DefaultRules" : {
  1412. "RateLimits" : {
  1413. "ReadBytesPerSecond": 16384,
  1414. "WriteBytesPerSecond": 16384,
  1415. "ReadUnthrottledBytes": %d,
  1416. "WriteUnthrottledBytes": %d
  1417. },
  1418. "AllowTCPPorts" : [0],
  1419. "AllowUDPPorts" : [0],
  1420. "MeekRateLimiterHistorySize" : 10,
  1421. "MeekRateLimiterThresholdSeconds" : 1,
  1422. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  1423. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  1424. "MeekRateLimiterRegions" : []
  1425. },
  1426. "FilteredRules" : [
  1427. {
  1428. "Filter" : {
  1429. "HandshakeParameters" : {
  1430. "propagation_channel_id" : ["%s"]
  1431. }%s
  1432. },
  1433. "Rules" : {
  1434. "RateLimits" : {
  1435. "ReadBytesPerSecond": 2097152,
  1436. "WriteBytesPerSecond": 2097152
  1437. },
  1438. "AllowTCPPorts" : [%s],
  1439. "AllowUDPPorts" : [%s],
  1440. "DisallowTCPPorts" : [%s],
  1441. "DisallowUDPPorts" : [%s]
  1442. }
  1443. }
  1444. ]
  1445. }
  1446. `
  1447. trafficRulesJSON := fmt.Sprintf(
  1448. trafficRulesJSONFormat,
  1449. livenessTestSize, livenessTestSize,
  1450. propagationChannelID, authorizationFilter,
  1451. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  1452. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  1453. if err != nil {
  1454. t.Fatalf("error paving traffic rules file: %s", err)
  1455. }
  1456. }
  1457. var expectedNumSLOKs = 3
  1458. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  1459. oslConfigJSONFormat := `
  1460. {
  1461. "Schemes" : [
  1462. {
  1463. "Epoch" : "%s",
  1464. "Regions" : [],
  1465. "PropagationChannelIDs" : ["%s"],
  1466. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  1467. "SeedSpecs" : [
  1468. {
  1469. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  1470. "UpstreamSubnets" : ["0.0.0.0/0"],
  1471. "Targets" :
  1472. {
  1473. "BytesRead" : 1,
  1474. "BytesWritten" : 1,
  1475. "PortForwardDurationNanoseconds" : 1
  1476. }
  1477. },
  1478. {
  1479. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  1480. "UpstreamSubnets" : ["0.0.0.0/0"],
  1481. "Targets" :
  1482. {
  1483. "BytesRead" : 1,
  1484. "BytesWritten" : 1,
  1485. "PortForwardDurationNanoseconds" : 1
  1486. }
  1487. }
  1488. ],
  1489. "SeedSpecThreshold" : 2,
  1490. "SeedPeriodNanoseconds" : 2592000000000000,
  1491. "SeedPeriodKeySplits": [
  1492. {
  1493. "Total": 2,
  1494. "Threshold": 2
  1495. }
  1496. ]
  1497. },
  1498. {
  1499. "Epoch" : "%s",
  1500. "Regions" : [],
  1501. "PropagationChannelIDs" : ["%s"],
  1502. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  1503. "SeedSpecs" : [
  1504. {
  1505. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  1506. "UpstreamSubnets" : ["0.0.0.0/0"],
  1507. "Targets" :
  1508. {
  1509. "BytesRead" : 1,
  1510. "BytesWritten" : 1,
  1511. "PortForwardDurationNanoseconds" : 1
  1512. }
  1513. }
  1514. ],
  1515. "SeedSpecThreshold" : 1,
  1516. "SeedPeriodNanoseconds" : 2592000000000000,
  1517. "SeedPeriodKeySplits": [
  1518. {
  1519. "Total": 1,
  1520. "Threshold": 1
  1521. }
  1522. ]
  1523. }
  1524. ]
  1525. }
  1526. `
  1527. propagationChannelID := prng.HexString(8)
  1528. now := time.Now().UTC()
  1529. epoch := now.Truncate(720 * time.Hour)
  1530. epochStr := epoch.Format(time.RFC3339Nano)
  1531. oslConfigJSON := fmt.Sprintf(
  1532. oslConfigJSONFormat,
  1533. epochStr, propagationChannelID,
  1534. epochStr, propagationChannelID)
  1535. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  1536. if err != nil {
  1537. t.Fatalf("error paving osl config file: %s", err)
  1538. }
  1539. return propagationChannelID
  1540. }
  1541. func paveTacticsConfigFile(
  1542. t *testing.T, tacticsConfigFilename string,
  1543. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey string,
  1544. tunnelProtocol string,
  1545. propagationChannelID string,
  1546. livenessTestSize int) {
  1547. // Setting LimitTunnelProtocols passively exercises the
  1548. // server-side LimitTunnelProtocols enforcement.
  1549. tacticsConfigJSONFormat := `
  1550. {
  1551. "RequestPublicKey" : "%s",
  1552. "RequestPrivateKey" : "%s",
  1553. "RequestObfuscatedKey" : "%s",
  1554. "EnforceServerSide" : true,
  1555. "DefaultTactics" : {
  1556. "TTL" : "60s",
  1557. "Probability" : 1.0,
  1558. "Parameters" : {
  1559. "LimitTunnelProtocols" : ["%s"],
  1560. "FragmentorLimitProtocols" : ["%s"],
  1561. "FragmentorProbability" : 1.0,
  1562. "FragmentorMinTotalBytes" : 1000,
  1563. "FragmentorMaxTotalBytes" : 2000,
  1564. "FragmentorMinWriteBytes" : 1,
  1565. "FragmentorMaxWriteBytes" : 100,
  1566. "FragmentorMinDelay" : "1ms",
  1567. "FragmentorMaxDelay" : "10ms",
  1568. "FragmentorDownstreamLimitProtocols" : ["%s"],
  1569. "FragmentorDownstreamProbability" : 1.0,
  1570. "FragmentorDownstreamMinTotalBytes" : 1000,
  1571. "FragmentorDownstreamMaxTotalBytes" : 2000,
  1572. "FragmentorDownstreamMinWriteBytes" : 1,
  1573. "FragmentorDownstreamMaxWriteBytes" : 100,
  1574. "FragmentorDownstreamMinDelay" : "1ms",
  1575. "FragmentorDownstreamMaxDelay" : "10ms",
  1576. "LivenessTestMinUpstreamBytes" : %d,
  1577. "LivenessTestMaxUpstreamBytes" : %d,
  1578. "LivenessTestMinDownstreamBytes" : %d,
  1579. "LivenessTestMaxDownstreamBytes" : %d,
  1580. "BPFServerTCPProgram": {
  1581. "Name" : "test-server-bpf",
  1582. "Instructions" : [
  1583. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1584. "BPFServerTCPProbability" : 1.0,
  1585. "BPFClientTCPProgram": {
  1586. "Name" : "test-client-bpf",
  1587. "Instructions" : [
  1588. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  1589. "BPFClientTCPProbability" : 1.0
  1590. }
  1591. },
  1592. "FilteredTactics" : [
  1593. {
  1594. "Filter" : {
  1595. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  1596. "SpeedTestRTTMilliseconds" : {
  1597. "Aggregation" : "Median",
  1598. "AtLeast" : 1
  1599. }
  1600. },
  1601. "Tactics" : {
  1602. "Parameters" : {
  1603. "TunnelConnectTimeout" : "20s",
  1604. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  1605. "TransformHostNameProbability" : 1.0,
  1606. "PickUserAgentProbability" : 1.0,
  1607. "ApplicationParameters" : {
  1608. "AppFlag1" : true,
  1609. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  1610. "AppSwitches1" : [1, 2, 3, 4]
  1611. }
  1612. }
  1613. }
  1614. }
  1615. ]
  1616. }
  1617. `
  1618. tacticsConfigJSON := fmt.Sprintf(
  1619. tacticsConfigJSONFormat,
  1620. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey,
  1621. tunnelProtocol,
  1622. tunnelProtocol,
  1623. tunnelProtocol,
  1624. livenessTestSize, livenessTestSize, livenessTestSize, livenessTestSize,
  1625. propagationChannelID)
  1626. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  1627. if err != nil {
  1628. t.Fatalf("error paving tactics config file: %s", err)
  1629. }
  1630. }
  1631. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  1632. blocklistContent :=
  1633. "255.255.255.255,test-source,test-subject\n2001:db8:f75c::0951:58bc:ef22,test-source,test-subject\nexample.org,test-source,test-subject\n"
  1634. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  1635. if err != nil {
  1636. t.Fatalf("error paving blocklist file: %s", err)
  1637. }
  1638. }
  1639. func sendNotificationReceived(c chan<- struct{}) {
  1640. select {
  1641. case c <- struct{}{}:
  1642. default:
  1643. }
  1644. }
  1645. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1646. if timeoutSignal == nil {
  1647. <-c
  1648. } else {
  1649. select {
  1650. case <-c:
  1651. case <-timeoutSignal:
  1652. t.Fatalf(timeoutMessage)
  1653. }
  1654. }
  1655. }
  1656. type pruneServerEntryTestCase struct {
  1657. IPAddress string
  1658. ExplicitTag bool
  1659. ExpectedTag string
  1660. LocalTimestamp string
  1661. PsinetValid bool
  1662. ExpectPrune bool
  1663. IsEmbedded bool
  1664. ServerEntryFields protocol.ServerEntryFields
  1665. }
  1666. func initializePruneServerEntriesTest(
  1667. t *testing.T,
  1668. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  1669. if !runConfig.doPruneServerEntries {
  1670. return nil, nil, 0
  1671. }
  1672. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  1673. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  1674. // Test Cases:
  1675. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  1676. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  1677. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  1678. // - ExpectPrune: prune outcome based on flags above
  1679. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  1680. // be reimported
  1681. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  1682. &pruneServerEntryTestCase{IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1683. &pruneServerEntryTestCase{IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  1684. &pruneServerEntryTestCase{IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1685. &pruneServerEntryTestCase{IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  1686. &pruneServerEntryTestCase{IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1687. &pruneServerEntryTestCase{IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  1688. &pruneServerEntryTestCase{IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1689. &pruneServerEntryTestCase{IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  1690. &pruneServerEntryTestCase{IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1691. &pruneServerEntryTestCase{IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  1692. }
  1693. for _, testCase := range pruneServerEntryTestCases {
  1694. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  1695. &GenerateConfigParams{
  1696. ServerIPAddress: testCase.IPAddress,
  1697. WebServerPort: 8000,
  1698. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: 4000},
  1699. })
  1700. if err != nil {
  1701. t.Fatalf("GenerateConfig failed: %s", err)
  1702. }
  1703. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  1704. if testCase.IsEmbedded {
  1705. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  1706. }
  1707. serverEntryFields, err := protocol.DecodeServerEntryFields(
  1708. string(encodedServerEntry),
  1709. testCase.LocalTimestamp,
  1710. serverEntrySource)
  1711. if err != nil {
  1712. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  1713. }
  1714. if testCase.ExplicitTag {
  1715. testCase.ExpectedTag = prng.Base64String(32)
  1716. serverEntryFields.SetTag(testCase.ExpectedTag)
  1717. } else {
  1718. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  1719. serverEntryFields.GetIPAddress(),
  1720. serverEntryFields.GetWebServerSecret())
  1721. }
  1722. testCase.ServerEntryFields = serverEntryFields
  1723. }
  1724. psinetValidServerEntryTags := make([]string, 0)
  1725. expectedNumPruneNotices := 0
  1726. for _, testCase := range pruneServerEntryTestCases {
  1727. if testCase.PsinetValid {
  1728. psinetValidServerEntryTags = append(
  1729. psinetValidServerEntryTags, testCase.ExpectedTag)
  1730. }
  1731. if testCase.ExpectPrune {
  1732. expectedNumPruneNotices += 1
  1733. }
  1734. }
  1735. return pruneServerEntryTestCases,
  1736. psinetValidServerEntryTags,
  1737. expectedNumPruneNotices
  1738. }
  1739. func storePruneServerEntriesTest(
  1740. t *testing.T,
  1741. runConfig *runServerConfig,
  1742. testDataDirName string,
  1743. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  1744. if !runConfig.doPruneServerEntries {
  1745. return
  1746. }
  1747. for _, testCase := range pruneServerEntryTestCases {
  1748. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1749. if err != nil {
  1750. t.Fatalf("StoreServerEntry failed: %s", err)
  1751. }
  1752. }
  1753. clientConfig := &psiphon.Config{
  1754. SponsorId: "0",
  1755. PropagationChannelId: "0",
  1756. // DataRootDirectory must to be set to avoid a migration in the current
  1757. // working directory.
  1758. DataRootDirectory: testDataDirName,
  1759. }
  1760. err := clientConfig.Commit(false)
  1761. if err != nil {
  1762. t.Fatalf("Commit failed: %s", err)
  1763. }
  1764. applyParameters := make(map[string]interface{})
  1765. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  1766. err = clientConfig.SetClientParameters("", true, applyParameters)
  1767. if err != nil {
  1768. t.Fatalf("SetClientParameters failed: %s", err)
  1769. }
  1770. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  1771. for _, testCase := range pruneServerEntryTestCases {
  1772. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1773. }
  1774. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1775. t *testing.T,
  1776. testCase *pruneServerEntryTestCase,
  1777. serverEntry *protocol.ServerEntry) {
  1778. verifyTestCasesStored.isStored(testCase.IPAddress)
  1779. // Check that random tag was retained or derived tag was calculated as
  1780. // expected
  1781. if serverEntry.Tag != testCase.ExpectedTag {
  1782. t.Fatalf("unexpected tag for %s got %s expected %s",
  1783. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  1784. }
  1785. // Create failed tunnel event records to exercise pruning
  1786. dialParams, err := psiphon.MakeDialParameters(
  1787. clientConfig,
  1788. func(_ *protocol.ServerEntry, _ string) bool { return true },
  1789. func(serverEntry *protocol.ServerEntry) (string, bool) {
  1790. return runConfig.tunnelProtocol, true
  1791. },
  1792. serverEntry,
  1793. false,
  1794. 0,
  1795. 0)
  1796. if err != nil {
  1797. t.Fatalf("MakeDialParameters failed: %s", err)
  1798. }
  1799. err = psiphon.RecordFailedTunnelStat(
  1800. clientConfig, dialParams, nil, 0, 0, errors.New("test error"))
  1801. if err != nil {
  1802. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  1803. }
  1804. })
  1805. verifyTestCasesStored.checkStored(
  1806. t, "missing prune test case server entries")
  1807. }
  1808. func checkPruneServerEntriesTest(
  1809. t *testing.T,
  1810. runConfig *runServerConfig,
  1811. testDataDirName string,
  1812. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  1813. if !runConfig.doPruneServerEntries {
  1814. return
  1815. }
  1816. clientConfig := &psiphon.Config{
  1817. SponsorId: "0",
  1818. PropagationChannelId: "0",
  1819. // DataRootDirectory must to be set to avoid a migration in the current
  1820. // working directory.
  1821. DataRootDirectory: testDataDirName,
  1822. }
  1823. err := clientConfig.Commit(false)
  1824. if err != nil {
  1825. t.Fatalf("Commit failed: %s", err)
  1826. }
  1827. // Check that server entries remain or are pruned as expected
  1828. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  1829. for _, testCase := range pruneServerEntryTestCases {
  1830. if !testCase.ExpectPrune {
  1831. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1832. }
  1833. }
  1834. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1835. t *testing.T,
  1836. testCase *pruneServerEntryTestCase,
  1837. serverEntry *protocol.ServerEntry) {
  1838. if testCase.ExpectPrune {
  1839. t.Fatalf("expected prune for %s", testCase.IPAddress)
  1840. } else {
  1841. verifyTestCasesStored.isStored(testCase.IPAddress)
  1842. }
  1843. })
  1844. verifyTestCasesStored.checkStored(
  1845. t, "missing prune test case server entries")
  1846. // Check that pruned server entries reimport or not, as expected
  1847. for _, testCase := range pruneServerEntryTestCases {
  1848. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1849. if err != nil {
  1850. t.Fatalf("StoreServerEntry failed: %s", err)
  1851. }
  1852. }
  1853. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  1854. for _, testCase := range pruneServerEntryTestCases {
  1855. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  1856. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1857. }
  1858. }
  1859. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1860. t *testing.T,
  1861. testCase *pruneServerEntryTestCase,
  1862. serverEntry *protocol.ServerEntry) {
  1863. if testCase.ExpectPrune && testCase.IsEmbedded {
  1864. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  1865. } else {
  1866. verifyTestCasesStored.isStored(testCase.IPAddress)
  1867. }
  1868. })
  1869. verifyTestCasesStored.checkStored(
  1870. t, "missing reimported prune test case server entries")
  1871. // Non-embedded server entries with tombstones _can_ be reimported
  1872. for _, testCase := range pruneServerEntryTestCases {
  1873. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  1874. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  1875. if err != nil {
  1876. t.Fatalf("StoreServerEntry failed: %s", err)
  1877. }
  1878. }
  1879. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  1880. for _, testCase := range pruneServerEntryTestCases {
  1881. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  1882. }
  1883. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  1884. t *testing.T,
  1885. testCase *pruneServerEntryTestCase,
  1886. serverEntry *protocol.ServerEntry) {
  1887. verifyTestCasesStored.isStored(testCase.IPAddress)
  1888. })
  1889. verifyTestCasesStored.checkStored(
  1890. t, "missing non-embedded reimported prune test case server entries")
  1891. }
  1892. func scanServerEntries(
  1893. t *testing.T,
  1894. clientConfig *psiphon.Config,
  1895. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  1896. scanner func(
  1897. t *testing.T,
  1898. testCase *pruneServerEntryTestCase,
  1899. serverEntry *protocol.ServerEntry)) {
  1900. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  1901. if err != nil {
  1902. t.Fatalf("NewServerEntryIterator failed: %s", err)
  1903. }
  1904. defer iterator.Close()
  1905. for {
  1906. serverEntry, err := iterator.Next()
  1907. if err != nil {
  1908. t.Fatalf("ServerIterator.Next failed: %s", err)
  1909. }
  1910. if serverEntry == nil {
  1911. break
  1912. }
  1913. for _, testCase := range pruneServerEntryTestCases {
  1914. if testCase.IPAddress == serverEntry.IpAddress {
  1915. scanner(t, testCase, serverEntry)
  1916. break
  1917. }
  1918. }
  1919. }
  1920. }
  1921. type verifyTestCasesStoredLookup map[string]bool
  1922. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  1923. v[s] = true
  1924. }
  1925. func (v verifyTestCasesStoredLookup) isStored(s string) {
  1926. delete(v, s)
  1927. }
  1928. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  1929. if len(v) != 0 {
  1930. t.Fatalf("%s: %+v", errMessage, v)
  1931. }
  1932. }