server_test.go 78 KB

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