server_test.go 94 KB

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