server_test.go 84 KB

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