server_test.go 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687
  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. "math"
  32. "net"
  33. "net/http"
  34. "net/url"
  35. "os"
  36. "path/filepath"
  37. "reflect"
  38. "regexp"
  39. "strconv"
  40. "strings"
  41. "sync"
  42. "syscall"
  43. "testing"
  44. "time"
  45. "unsafe"
  46. socks "github.com/Psiphon-Labs/goptlib"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  48. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  49. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  50. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  51. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  52. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  53. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  54. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  55. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  56. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  57. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  58. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  59. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server/psinet"
  60. lrucache "github.com/cognusion/go-cache-lru"
  61. "github.com/miekg/dns"
  62. "golang.org/x/net/proxy"
  63. )
  64. var testDataDirName string
  65. var mockWebServerURL, mockWebServerPort, mockWebServerExpectedResponse string
  66. func TestMain(m *testing.M) {
  67. flag.Parse()
  68. var err error
  69. testDataDirName, err = ioutil.TempDir("", "psiphon-server-test")
  70. if err != nil {
  71. fmt.Printf("TempDir failed: %s\n", err)
  72. os.Exit(1)
  73. }
  74. defer os.RemoveAll(testDataDirName)
  75. psiphon.SetEmitDiagnosticNotices(true, true)
  76. mockWebServerURL, mockWebServerExpectedResponse = runMockWebServer()
  77. os.Exit(m.Run())
  78. }
  79. func runMockWebServer() (string, string) {
  80. responseBody := prng.HexString(100000)
  81. serveMux := http.NewServeMux()
  82. serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  83. w.Write([]byte(responseBody))
  84. })
  85. server := &http.Server{
  86. Handler: serveMux,
  87. }
  88. listener, err := net.Listen("tcp", "127.0.0.1:0")
  89. if err != nil {
  90. fmt.Printf("net.Listen failed: %s\n", err)
  91. os.Exit(1)
  92. }
  93. listenAddress := listener.Addr().String()
  94. _, mockWebServerPort, _ = net.SplitHostPort(listenAddress)
  95. go func() {
  96. err := server.Serve(listener)
  97. if err != nil {
  98. fmt.Printf("http.Server.Serve failed: %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/", listenAddress), 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. requireAuthorization: true,
  113. doTunneledWebRequest: true,
  114. doTunneledNTPRequest: true,
  115. doDanglingTCPConn: true,
  116. doLogHostProvider: true,
  117. })
  118. }
  119. func TestOSSH(t *testing.T) {
  120. runServer(t,
  121. &runServerConfig{
  122. tunnelProtocol: "OSSH",
  123. requireAuthorization: true,
  124. doTunneledWebRequest: true,
  125. doTunneledNTPRequest: true,
  126. doDanglingTCPConn: true,
  127. doLogHostProvider: true,
  128. })
  129. }
  130. func TestFragmentedOSSH(t *testing.T) {
  131. runServer(t,
  132. &runServerConfig{
  133. tunnelProtocol: "OSSH",
  134. requireAuthorization: true,
  135. doTunneledWebRequest: true,
  136. doTunneledNTPRequest: true,
  137. forceFragmenting: true,
  138. doDanglingTCPConn: true,
  139. doLogHostProvider: true,
  140. })
  141. }
  142. func TestPrefixedOSSH(t *testing.T) {
  143. runServer(t,
  144. &runServerConfig{
  145. tunnelProtocol: "OSSH",
  146. requireAuthorization: true,
  147. doTunneledWebRequest: true,
  148. doTunneledNTPRequest: true,
  149. applyPrefix: true,
  150. doDanglingTCPConn: true,
  151. doLogHostProvider: true,
  152. inspectFlows: true,
  153. })
  154. }
  155. func TestFragmentedPrefixedOSSH(t *testing.T) {
  156. runServer(t,
  157. &runServerConfig{
  158. tunnelProtocol: "OSSH",
  159. requireAuthorization: true,
  160. doTunneledWebRequest: true,
  161. doTunneledNTPRequest: true,
  162. applyPrefix: true,
  163. forceFragmenting: true,
  164. doDanglingTCPConn: true,
  165. doLogHostProvider: true,
  166. inspectFlows: true,
  167. })
  168. }
  169. // NOTE: breaks the naming convention of dropping the OSSH suffix
  170. // because TestTLS is ambiguous as there are other protocols which
  171. // use TLS, e.g. UNFRONTED-MEEK-HTTPS-OSSH.
  172. func TestTLSOSSH(t *testing.T) {
  173. runServer(t,
  174. &runServerConfig{
  175. tunnelProtocol: "TLS-OSSH",
  176. passthrough: true,
  177. requireAuthorization: true,
  178. doTunneledWebRequest: true,
  179. doTunneledNTPRequest: true,
  180. doDanglingTCPConn: true,
  181. })
  182. }
  183. func TestShadowsocks(t *testing.T) {
  184. runServer(t,
  185. &runServerConfig{
  186. tunnelProtocol: "SHADOWSOCKS-OSSH",
  187. requireAuthorization: true,
  188. doTunneledWebRequest: true,
  189. doTunneledNTPRequest: true,
  190. doDanglingTCPConn: true,
  191. applyPrefix: true,
  192. })
  193. }
  194. func TestUnfrontedMeek(t *testing.T) {
  195. runServer(t,
  196. &runServerConfig{
  197. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  198. requireAuthorization: true,
  199. doTunneledWebRequest: true,
  200. doTunneledNTPRequest: true,
  201. doDanglingTCPConn: true,
  202. doLogHostProvider: true,
  203. })
  204. }
  205. func TestFragmentedUnfrontedMeek(t *testing.T) {
  206. runServer(t,
  207. &runServerConfig{
  208. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  209. requireAuthorization: true,
  210. doTunneledWebRequest: true,
  211. doTunneledNTPRequest: true,
  212. forceFragmenting: true,
  213. doDanglingTCPConn: true,
  214. doLogHostProvider: true,
  215. })
  216. }
  217. func TestUnfrontedMeekHTTPS(t *testing.T) {
  218. runServer(t,
  219. &runServerConfig{
  220. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  221. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  222. requireAuthorization: true,
  223. doTunneledWebRequest: true,
  224. doTunneledNTPRequest: true,
  225. doDanglingTCPConn: true,
  226. doLogHostProvider: true,
  227. })
  228. }
  229. func TestFragmentedUnfrontedMeekHTTPS(t *testing.T) {
  230. runServer(t,
  231. &runServerConfig{
  232. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  233. tlsProfile: protocol.TLS_PROFILE_RANDOMIZED,
  234. requireAuthorization: true,
  235. doTunneledWebRequest: true,
  236. doTunneledNTPRequest: true,
  237. forceFragmenting: true,
  238. doDanglingTCPConn: true,
  239. doLogHostProvider: true,
  240. })
  241. }
  242. func TestUnfrontedMeekHTTPSTLS13(t *testing.T) {
  243. runServer(t,
  244. &runServerConfig{
  245. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  246. tlsProfile: protocol.TLS_PROFILE_CHROME_70,
  247. requireAuthorization: true,
  248. doTunneledWebRequest: true,
  249. doTunneledNTPRequest: true,
  250. doDanglingTCPConn: true,
  251. doLogHostProvider: true,
  252. })
  253. }
  254. func TestUnfrontedMeekSessionTicket(t *testing.T) {
  255. runServer(t,
  256. &runServerConfig{
  257. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  258. tlsProfile: protocol.TLS_PROFILE_CHROME_58,
  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. requireAuthorization: true,
  272. doTunneledWebRequest: true,
  273. doTunneledNTPRequest: true,
  274. doDanglingTCPConn: true,
  275. doLogHostProvider: true,
  276. })
  277. }
  278. func TestTLSOSSHOverUnfrontedMeekHTTPSDemux(t *testing.T) {
  279. runServer(t,
  280. &runServerConfig{
  281. tunnelProtocol: "UNFRONTED-MEEK-HTTPS-OSSH",
  282. clientTunnelProtocol: "TLS-OSSH",
  283. passthrough: true,
  284. tlsProfile: protocol.TLS_PROFILE_CHROME_96, // TLS-OSSH requires TLS 1.3 support
  285. requireAuthorization: true,
  286. doTunneledWebRequest: true,
  287. doTunneledNTPRequest: true,
  288. doDanglingTCPConn: true,
  289. })
  290. }
  291. func TestTLSOSSHOverUnfrontedMeekSessionTicketDemux(t *testing.T) {
  292. runServer(t,
  293. &runServerConfig{
  294. tunnelProtocol: "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  295. clientTunnelProtocol: "TLS-OSSH",
  296. passthrough: true,
  297. tlsProfile: protocol.TLS_PROFILE_CHROME_96, // TLS-OSSH requires TLS 1.3 support
  298. requireAuthorization: true,
  299. doTunneledWebRequest: true,
  300. doTunneledNTPRequest: true,
  301. doDanglingTCPConn: true,
  302. })
  303. }
  304. func TestQUICOSSH(t *testing.T) {
  305. if !quic.Enabled() {
  306. t.Skip("QUIC is not enabled")
  307. }
  308. runServer(t,
  309. &runServerConfig{
  310. tunnelProtocol: "QUIC-OSSH",
  311. requireAuthorization: true,
  312. doTunneledWebRequest: true,
  313. doTunneledNTPRequest: true,
  314. doLogHostProvider: true,
  315. })
  316. }
  317. func TestLimitedQUICOSSH(t *testing.T) {
  318. if !quic.Enabled() {
  319. t.Skip("QUIC is not enabled")
  320. }
  321. runServer(t,
  322. &runServerConfig{
  323. tunnelProtocol: "QUIC-OSSH",
  324. requireAuthorization: true,
  325. doTunneledWebRequest: true,
  326. doTunneledNTPRequest: true,
  327. limitQUICVersions: true,
  328. doLogHostProvider: true,
  329. })
  330. }
  331. func TestInproxyOSSH(t *testing.T) {
  332. if !inproxy.Enabled() {
  333. t.Skip("inproxy is not enabled")
  334. }
  335. runServer(t,
  336. &runServerConfig{
  337. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  338. requireAuthorization: true,
  339. doTunneledWebRequest: true,
  340. doTunneledNTPRequest: true,
  341. doDanglingTCPConn: true,
  342. doLogHostProvider: true,
  343. doTargetBrokerSpecs: true,
  344. })
  345. }
  346. func TestRestrictInproxy(t *testing.T) {
  347. if !inproxy.Enabled() {
  348. t.Skip("inproxy is not enabled")
  349. }
  350. runServer(t,
  351. &runServerConfig{
  352. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  353. doRestrictInproxy: true,
  354. })
  355. }
  356. func TestInproxyQUICOSSH(t *testing.T) {
  357. if !quic.Enabled() {
  358. t.Skip("QUIC is not enabled")
  359. }
  360. if !inproxy.Enabled() {
  361. t.Skip("inproxy is not enabled")
  362. }
  363. runServer(t,
  364. &runServerConfig{
  365. tunnelProtocol: "INPROXY-WEBRTC-QUIC-OSSH",
  366. requireAuthorization: true,
  367. doTunneledWebRequest: true,
  368. doTunneledNTPRequest: true,
  369. doLogHostProvider: true,
  370. })
  371. }
  372. func TestInproxyUnfrontedMeekHTTPS(t *testing.T) {
  373. if !inproxy.Enabled() {
  374. t.Skip("inproxy is not enabled")
  375. }
  376. runServer(t,
  377. &runServerConfig{
  378. tunnelProtocol: "INPROXY-WEBRTC-UNFRONTED-MEEK-HTTPS-OSSH",
  379. requireAuthorization: true,
  380. doTunneledWebRequest: true,
  381. doTunneledNTPRequest: true,
  382. doDanglingTCPConn: true,
  383. doLogHostProvider: true,
  384. })
  385. }
  386. func TestInproxyTLSOSSH(t *testing.T) {
  387. if !inproxy.Enabled() {
  388. t.Skip("inproxy is not enabled")
  389. }
  390. runServer(t,
  391. &runServerConfig{
  392. tunnelProtocol: "INPROXY-WEBRTC-TLS-OSSH",
  393. requireAuthorization: true,
  394. doTunneledWebRequest: true,
  395. doTunneledNTPRequest: true,
  396. doDanglingTCPConn: true,
  397. doLogHostProvider: true,
  398. })
  399. }
  400. func TestInproxyPersonalPairing(t *testing.T) {
  401. if !inproxy.Enabled() {
  402. t.Skip("inproxy is not enabled")
  403. }
  404. runServer(t,
  405. &runServerConfig{
  406. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  407. requireAuthorization: true,
  408. doTunneledWebRequest: true,
  409. doTunneledNTPRequest: true,
  410. doDanglingTCPConn: true,
  411. doLogHostProvider: true,
  412. doTargetBrokerSpecs: true,
  413. doPersonalPairing: true,
  414. })
  415. }
  416. func TestInproxyOSSHMediaStreams(t *testing.T) {
  417. if !inproxy.Enabled() {
  418. t.Skip("inproxy is not enabled")
  419. }
  420. runServer(t,
  421. &runServerConfig{
  422. tunnelProtocol: "INPROXY-WEBRTC-OSSH",
  423. requireAuthorization: true,
  424. doTunneledWebRequest: true,
  425. doTunneledNTPRequest: true,
  426. doDanglingTCPConn: true,
  427. doLogHostProvider: true,
  428. doTargetBrokerSpecs: true,
  429. useInproxyMediaStreams: true,
  430. })
  431. }
  432. func TestInproxyQUICOSSHMediaStreams(t *testing.T) {
  433. if !inproxy.Enabled() {
  434. t.Skip("inproxy is not enabled")
  435. }
  436. runServer(t,
  437. &runServerConfig{
  438. tunnelProtocol: "INPROXY-WEBRTC-QUIC-OSSH",
  439. requireAuthorization: true,
  440. doTunneledWebRequest: true,
  441. doTunneledNTPRequest: true,
  442. doLogHostProvider: true,
  443. doTargetBrokerSpecs: true,
  444. useInproxyMediaStreams: true,
  445. })
  446. }
  447. func TestHotReload(t *testing.T) {
  448. runServer(t,
  449. &runServerConfig{
  450. tunnelProtocol: "OSSH",
  451. doHotReload: true,
  452. requireAuthorization: true,
  453. doTunneledWebRequest: true,
  454. doTunneledNTPRequest: true,
  455. doLogHostProvider: true,
  456. })
  457. }
  458. func TestHotReloadWithTactics(t *testing.T) {
  459. runServer(t,
  460. &runServerConfig{
  461. tunnelProtocol: "UNFRONTED-MEEK-OSSH",
  462. doHotReload: true,
  463. requireAuthorization: true,
  464. doTunneledWebRequest: true,
  465. doTunneledNTPRequest: true,
  466. doLogHostProvider: true,
  467. })
  468. }
  469. func TestDefaultSponsorID(t *testing.T) {
  470. runServer(t,
  471. &runServerConfig{
  472. tunnelProtocol: "OSSH",
  473. doHotReload: true,
  474. doDefaultSponsorID: true,
  475. requireAuthorization: true,
  476. doTunneledWebRequest: true,
  477. doTunneledNTPRequest: true,
  478. doLogHostProvider: true,
  479. })
  480. }
  481. func TestDenyTrafficRules(t *testing.T) {
  482. runServer(t,
  483. &runServerConfig{
  484. tunnelProtocol: "OSSH",
  485. doHotReload: true,
  486. denyTrafficRules: true,
  487. requireAuthorization: true,
  488. doTunneledWebRequest: true,
  489. doTunneledNTPRequest: true,
  490. doLogHostProvider: true,
  491. })
  492. }
  493. func TestOmitAuthorization(t *testing.T) {
  494. runServer(t,
  495. &runServerConfig{
  496. tunnelProtocol: "OSSH",
  497. doHotReload: true,
  498. requireAuthorization: true,
  499. omitAuthorization: true,
  500. doTunneledWebRequest: true,
  501. doTunneledNTPRequest: true,
  502. doLogHostProvider: true,
  503. })
  504. }
  505. func TestNoAuthorization(t *testing.T) {
  506. runServer(t,
  507. &runServerConfig{
  508. tunnelProtocol: "OSSH",
  509. doHotReload: true,
  510. omitAuthorization: true,
  511. doTunneledWebRequest: true,
  512. doTunneledNTPRequest: true,
  513. doLogHostProvider: true,
  514. })
  515. }
  516. func TestUnusedAuthorization(t *testing.T) {
  517. runServer(t,
  518. &runServerConfig{
  519. tunnelProtocol: "OSSH",
  520. doHotReload: true,
  521. doTunneledWebRequest: true,
  522. doTunneledNTPRequest: true,
  523. doLogHostProvider: true,
  524. })
  525. }
  526. func TestTCPOnlySLOK(t *testing.T) {
  527. runServer(t,
  528. &runServerConfig{
  529. tunnelProtocol: "OSSH",
  530. requireAuthorization: true,
  531. doTunneledWebRequest: true,
  532. doLogHostProvider: true,
  533. })
  534. }
  535. func TestUDPOnlySLOK(t *testing.T) {
  536. runServer(t,
  537. &runServerConfig{
  538. tunnelProtocol: "OSSH",
  539. requireAuthorization: true,
  540. doTunneledNTPRequest: true,
  541. doLogHostProvider: true,
  542. })
  543. }
  544. func TestLivenessTest(t *testing.T) {
  545. runServer(t,
  546. &runServerConfig{
  547. tunnelProtocol: "OSSH",
  548. requireAuthorization: true,
  549. doTunneledWebRequest: true,
  550. doTunneledNTPRequest: true,
  551. forceLivenessTest: true,
  552. doLogHostProvider: true,
  553. })
  554. }
  555. func TestPruneServerEntries(t *testing.T) {
  556. runServer(t,
  557. &runServerConfig{
  558. tunnelProtocol: "OSSH",
  559. requireAuthorization: true,
  560. doTunneledWebRequest: true,
  561. doTunneledNTPRequest: true,
  562. forceLivenessTest: true,
  563. doPruneServerEntries: true,
  564. doLogHostProvider: true,
  565. })
  566. }
  567. func TestBurstMonitorAndDestinationBytes(t *testing.T) {
  568. runServer(t,
  569. &runServerConfig{
  570. tunnelProtocol: "OSSH",
  571. requireAuthorization: true,
  572. doTunneledWebRequest: true,
  573. doTunneledNTPRequest: true,
  574. doDanglingTCPConn: true,
  575. doBurstMonitor: true,
  576. doDestinationBytes: true,
  577. doLogHostProvider: true,
  578. })
  579. }
  580. func TestBurstMonitorAndLegacyDestinationBytes(t *testing.T) {
  581. runServer(t,
  582. &runServerConfig{
  583. tunnelProtocol: "OSSH",
  584. requireAuthorization: true,
  585. doTunneledWebRequest: true,
  586. doTunneledNTPRequest: true,
  587. doDanglingTCPConn: true,
  588. doBurstMonitor: true,
  589. doLegacyDestinationBytes: true,
  590. doLogHostProvider: true,
  591. })
  592. }
  593. func TestChangeBytesConfig(t *testing.T) {
  594. runServer(t,
  595. &runServerConfig{
  596. tunnelProtocol: "OSSH",
  597. requireAuthorization: true,
  598. doTunneledWebRequest: true,
  599. doTunneledNTPRequest: true,
  600. doDanglingTCPConn: true,
  601. doDestinationBytes: true,
  602. doLegacyDestinationBytes: true,
  603. doChangeBytesConfig: true,
  604. doLogHostProvider: true,
  605. })
  606. }
  607. func TestSplitTunnel(t *testing.T) {
  608. runServer(t,
  609. &runServerConfig{
  610. tunnelProtocol: "OSSH",
  611. requireAuthorization: true,
  612. doTunneledWebRequest: true,
  613. doTunneledNTPRequest: true,
  614. doDanglingTCPConn: true,
  615. doSplitTunnel: true,
  616. doLogHostProvider: true,
  617. })
  618. }
  619. func TestOmitProvider(t *testing.T) {
  620. runServer(t,
  621. &runServerConfig{
  622. tunnelProtocol: "OSSH",
  623. requireAuthorization: true,
  624. doTunneledWebRequest: true,
  625. doTunneledNTPRequest: true,
  626. doDanglingTCPConn: true,
  627. })
  628. }
  629. func TestSteeringIP(t *testing.T) {
  630. runServer(t,
  631. &runServerConfig{
  632. tunnelProtocol: "FRONTED-MEEK-OSSH",
  633. // use a TLS profile that offers h2 in the ALPN
  634. tlsProfile: protocol.TLS_PROFILE_CHROME_102,
  635. requireAuthorization: true,
  636. doTunneledWebRequest: true,
  637. doTunneledNTPRequest: true,
  638. forceFragmenting: true,
  639. doDanglingTCPConn: true,
  640. doLogHostProvider: true,
  641. doSteeringIP: true,
  642. })
  643. }
  644. func TestLegacyAPIEncoding(t *testing.T) {
  645. runServer(t,
  646. &runServerConfig{
  647. tunnelProtocol: "OSSH",
  648. requireAuthorization: true,
  649. doTunneledWebRequest: true,
  650. doTunneledNTPRequest: true,
  651. doDanglingTCPConn: true,
  652. doLogHostProvider: true,
  653. useLegacyAPIEncoding: true,
  654. })
  655. }
  656. func TestDomainRequest(t *testing.T) {
  657. runServer(t,
  658. &runServerConfig{
  659. tunnelProtocol: "SSH",
  660. requireAuthorization: true,
  661. doTunneledDomainRequest: true,
  662. doLogHostProvider: true,
  663. })
  664. }
  665. type runServerConfig struct {
  666. tunnelProtocol string
  667. clientTunnelProtocol string
  668. passthrough bool
  669. tlsProfile string
  670. doHotReload bool
  671. doDefaultSponsorID bool
  672. denyTrafficRules bool
  673. requireAuthorization bool
  674. omitAuthorization bool
  675. doTunneledWebRequest bool
  676. doTunneledDomainRequest bool
  677. doTunneledNTPRequest bool
  678. applyPrefix bool
  679. forceFragmenting bool
  680. forceLivenessTest bool
  681. doPruneServerEntries bool
  682. doDanglingTCPConn bool
  683. doPacketManipulation bool
  684. doBurstMonitor bool
  685. doSplitTunnel bool
  686. limitQUICVersions bool
  687. doDestinationBytes bool
  688. doLegacyDestinationBytes bool
  689. doChangeBytesConfig bool
  690. doLogHostProvider bool
  691. inspectFlows bool
  692. doSteeringIP bool
  693. doTargetBrokerSpecs bool
  694. useLegacyAPIEncoding bool
  695. doPersonalPairing bool
  696. doRestrictInproxy bool
  697. useInproxyMediaStreams bool
  698. }
  699. var (
  700. testSSHClientVersions = []string{"SSH-2.0-A", "SSH-2.0-B", "SSH-2.0-C"}
  701. testUserAgents = []string{"ua1", "ua2", "ua3"}
  702. testNetworkType = "WIFI"
  703. testCustomHostNameRegex = `[a-z0-9]{5,10}\.example\.org`
  704. testClientVersion = 1
  705. testClientPlatform = "Android_10_com.test.app"
  706. testClientFeatures = []string{"feature 1", "feature 2"}
  707. testDeviceRegion = "US"
  708. testDeviceLocation = "gzzzz"
  709. testDisallowedTrafficAlertActionURLs = []string{"https://example.org/disallowed"}
  710. // A steering IP must not be a bogon; this address is not dialed.
  711. testSteeringIP = "1.1.1.1"
  712. )
  713. var lastConnectedUpdateCount = 0
  714. func runServer(t *testing.T, runConfig *runServerConfig) {
  715. psiphonServerIPAddress := "127.0.0.1"
  716. psiphonServerPort := 4000
  717. // initialize server entry signing
  718. serverEntrySignaturePublicKey,
  719. serverEntrySignaturePrivateKey, err := protocol.NewServerEntrySignatureKeyPair()
  720. if err != nil {
  721. t.Fatalf("error generating server entry signature key pair: %s", err)
  722. }
  723. // generate inproxy configuration
  724. doInproxy := protocol.TunnelProtocolUsesInproxy(runConfig.tunnelProtocol)
  725. var inproxyTestConfig *inproxyTestConfig
  726. if doInproxy {
  727. addMeekServerForBroker := true
  728. brokerIPAddress := "127.0.0.1"
  729. brokerPort := 4001
  730. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  731. // Use the existing meek server as the broker server
  732. addMeekServerForBroker = false
  733. brokerPort = 4000
  734. }
  735. var err error
  736. inproxyTestConfig, err = generateInproxyTestConfig(
  737. addMeekServerForBroker,
  738. runConfig.doTargetBrokerSpecs,
  739. brokerIPAddress,
  740. brokerPort,
  741. serverEntrySignaturePublicKey,
  742. runConfig.useInproxyMediaStreams)
  743. if err != nil {
  744. t.Fatalf("error generating inproxy test config: %s", err)
  745. }
  746. }
  747. // configure authorized access
  748. accessType := "test-access-type"
  749. accessControlSigningKey, accessControlVerificationKey, err := accesscontrol.NewKeyPair(accessType)
  750. if err != nil {
  751. t.Fatalf("error creating access control key pair: %s", err)
  752. }
  753. accessControlVerificationKeyRing := accesscontrol.VerificationKeyRing{
  754. Keys: []*accesscontrol.VerificationKey{accessControlVerificationKey},
  755. }
  756. var seedAuthorizationID [32]byte
  757. clientAuthorization, authorizationID, err := accesscontrol.IssueAuthorization(
  758. accessControlSigningKey,
  759. seedAuthorizationID[:],
  760. time.Now().Add(1*time.Hour))
  761. if err != nil {
  762. t.Fatalf("error issuing authorization: %s", err)
  763. }
  764. authorizationIDStr := base64.StdEncoding.EncodeToString(authorizationID)
  765. // Enable tactics when the test protocol is meek or uses inproxy. Both the
  766. // client and the server will be configured to support tactics. The
  767. // client config will be set with a nonfunctional config so that the
  768. // tactics request must succeed, overriding the nonfunctional values, for
  769. // the tunnel to establish.
  770. doClientTactics := protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) ||
  771. doInproxy
  772. doServerTactics := doClientTactics ||
  773. runConfig.applyPrefix ||
  774. runConfig.forceFragmenting ||
  775. runConfig.doBurstMonitor ||
  776. runConfig.doDestinationBytes ||
  777. runConfig.doLegacyDestinationBytes ||
  778. runConfig.doTunneledDomainRequest
  779. // All servers require a tactics config with valid keys.
  780. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err :=
  781. tactics.GenerateKeys()
  782. if err != nil {
  783. t.Fatalf("error generating tactics keys: %s", err)
  784. }
  785. livenessTestSize := 0
  786. if doClientTactics || runConfig.forceLivenessTest {
  787. livenessTestSize = 1048576
  788. }
  789. // create a server
  790. var limitQUICVersions protocol.QUICVersions
  791. if runConfig.limitQUICVersions {
  792. // Limit the server entry to one specific QUICv1 version, and check
  793. // that this is used (see expectQUICVersion below). This test case
  794. // also exercises disabling gQUIC in the server config and
  795. // using "QUICv1" as the server entry capability.
  796. selectedQUICVersion := protocol.SupportedQUICv1Versions[prng.Intn(
  797. len(protocol.SupportedQUICv1Versions))]
  798. limitQUICVersions = protocol.QUICVersions{selectedQUICVersion}
  799. }
  800. var tunnelProtocolPassthroughAddresses map[string]string
  801. var passthroughAddress *string
  802. if runConfig.passthrough {
  803. passthroughAddress = new(string)
  804. *passthroughAddress = "x.x.x.x:x"
  805. tunnelProtocolPassthroughAddresses = map[string]string{
  806. // Tests do not trigger passthrough so set invalid IP and port.
  807. runConfig.tunnelProtocol: *passthroughAddress,
  808. }
  809. }
  810. tunnelProtocolPorts := map[string]int{runConfig.tunnelProtocol: psiphonServerPort}
  811. if doInproxy && inproxyTestConfig.addMeekServerForBroker {
  812. tunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"] = inproxyTestConfig.brokerPort
  813. }
  814. generateConfigParams := &GenerateConfigParams{
  815. ServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  816. ServerEntrySignaturePrivateKey: serverEntrySignaturePrivateKey,
  817. ServerIPAddress: psiphonServerIPAddress,
  818. TunnelProtocolPorts: tunnelProtocolPorts,
  819. TunnelProtocolPassthroughAddresses: tunnelProtocolPassthroughAddresses,
  820. Passthrough: runConfig.passthrough,
  821. LimitQUICVersions: limitQUICVersions,
  822. EnableGQUIC: !runConfig.limitQUICVersions,
  823. }
  824. if doServerTactics {
  825. generateConfigParams.TacticsRequestPublicKey = tacticsRequestPublicKey
  826. generateConfigParams.TacticsRequestObfuscatedKey = tacticsRequestObfuscatedKey
  827. }
  828. if protocol.TunnelProtocolUsesFrontedMeek(runConfig.tunnelProtocol) {
  829. generateConfigParams.FrontingProviderID = prng.HexString(8)
  830. }
  831. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  832. if err != nil {
  833. t.Fatalf("error generating server config: %s", err)
  834. }
  835. // customize server config
  836. discoveryServers, err := newDiscoveryServers([]string{"1.1.1.1", "2.2.2.2"})
  837. if err != nil {
  838. t.Fatalf("newDiscoveryServers failed: %s\n", err)
  839. }
  840. // Initialize prune server entry test cases and associated data to pave into psinet.
  841. pruneServerEntryTestCases, psinetValidServerEntryTags, expectedNumPruneNotices :=
  842. initializePruneServerEntriesTest(t, runConfig)
  843. // Pave psinet with random values to test handshake homepages.
  844. psinetFilename := filepath.Join(testDataDirName, "psinet.json")
  845. sponsorID, expectedHomepageURL := pavePsinetDatabaseFile(
  846. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags, discoveryServers)
  847. // Pave OSL config for SLOK testing
  848. oslConfigFilename := filepath.Join(testDataDirName, "osl_config.json")
  849. propagationChannelID := paveOSLConfigFile(t, oslConfigFilename)
  850. // Pave traffic rules file which exercises handshake parameter filtering. Client
  851. // must handshake with specified sponsor ID in order to allow ports for tunneled
  852. // requests.
  853. trafficRulesFilename := filepath.Join(testDataDirName, "traffic_rules.json")
  854. paveTrafficRulesFile(
  855. t,
  856. trafficRulesFilename,
  857. propagationChannelID,
  858. accessType,
  859. authorizationIDStr,
  860. runConfig.requireAuthorization,
  861. runConfig.denyTrafficRules,
  862. livenessTestSize)
  863. var tacticsConfigFilename string
  864. var tacticsTunnelProtocol string
  865. var inproxyTacticsParametersJSON string
  866. // Only pave the tactics config when tactics are required. This exercises the
  867. // case where the tactics config is omitted.
  868. if doServerTactics {
  869. tacticsConfigFilename = filepath.Join(testDataDirName, "tactics_config.json")
  870. if runConfig.clientTunnelProtocol != "" {
  871. tacticsTunnelProtocol = runConfig.clientTunnelProtocol
  872. } else {
  873. tacticsTunnelProtocol = runConfig.tunnelProtocol
  874. }
  875. if doInproxy {
  876. inproxyTacticsParametersJSON = inproxyTestConfig.tacticsParametersJSON
  877. }
  878. paveTacticsConfigFile(
  879. t,
  880. tacticsConfigFilename,
  881. tacticsRequestPublicKey,
  882. tacticsRequestPrivateKey,
  883. tacticsRequestObfuscatedKey,
  884. tacticsTunnelProtocol,
  885. propagationChannelID,
  886. livenessTestSize,
  887. runConfig.doBurstMonitor,
  888. runConfig.doDestinationBytes,
  889. runConfig.doLegacyDestinationBytes,
  890. runConfig.applyPrefix,
  891. runConfig.forceFragmenting,
  892. "classic",
  893. inproxyTacticsParametersJSON,
  894. runConfig.doRestrictInproxy)
  895. }
  896. blocklistFilename := filepath.Join(testDataDirName, "blocklist.csv")
  897. paveBlocklistFile(t, blocklistFilename)
  898. var serverConfig map[string]interface{}
  899. json.Unmarshal(serverConfigJSON, &serverConfig)
  900. // The test GeoIP databases map all IPs to a single, non-"None" country
  901. // and ASN.
  902. //
  903. // When split tunnel mode is enabled, this should cause port forwards to
  904. // be untunneled. When split tunnel mode is not enabled, port forwards
  905. // should be tunneled despite the country match.
  906. //
  907. // When destination bytes metrics are enabled, all traffic will map to the
  908. // single ASN.
  909. geoIPCityDatabaseFilename := filepath.Join(testDataDirName, "geoip_city_database.mmbd")
  910. geoIPISPDatabaseFilename := filepath.Join(testDataDirName, "geoip_isp_database.mmbd")
  911. paveGeoIPDatabaseFiles(t, geoIPCityDatabaseFilename, geoIPISPDatabaseFilename)
  912. serverConfig["GeoIPDatabaseFilenames"] = []string{geoIPCityDatabaseFilename, geoIPISPDatabaseFilename}
  913. serverConfig["PsinetDatabaseFilename"] = psinetFilename
  914. serverConfig["TrafficRulesFilename"] = trafficRulesFilename
  915. serverConfig["OSLConfigFilename"] = oslConfigFilename
  916. if doServerTactics {
  917. serverConfig["TacticsConfigFilename"] = tacticsConfigFilename
  918. }
  919. serverConfig["BlocklistFilename"] = blocklistFilename
  920. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  921. serverConfig["LogLevel"] = "debug"
  922. serverConfig["AccessControlVerificationKeyRing"] = accessControlVerificationKeyRing
  923. // Set this parameter so at least the semaphore functions are called.
  924. // TODO: test that the concurrency limit is correctly enforced.
  925. serverConfig["MaxConcurrentSSHHandshakes"] = 1
  926. // Ensure peak failure rate log fields for a single port forward attempt
  927. serverConfig["PeakUpstreamFailureRateMinimumSampleSize"] = 1
  928. // Exercise this option.
  929. serverConfig["PeriodicGarbageCollectionSeconds"] = 1
  930. // Allow port forwards to local test web server.
  931. serverConfig["AllowBogons"] = true
  932. serverConfig["RunPacketManipulator"] = runConfig.doPacketManipulation
  933. if protocol.TunnelProtocolUsesQUIC(runConfig.tunnelProtocol) &&
  934. !runConfig.limitQUICVersions &&
  935. quic.GQUICEnabled() {
  936. // Enable legacy QUIC version support.
  937. serverConfig["EnableGQUIC"] = true
  938. }
  939. if runConfig.doLogHostProvider {
  940. serverConfig["HostProvider"] = "example-host-provider"
  941. }
  942. if runConfig.doSteeringIP {
  943. serverConfig["EnableSteeringIPs"] = true
  944. }
  945. // In-proxy setup.
  946. if doInproxy {
  947. serverConfig["MeekServerRunInproxyBroker"] = true
  948. // Limitation: can't exercise MeekServerInproxyBrokerOnly, as the
  949. // single meek server must also provide a tactics endpoint.
  950. serverConfig["MeekServerCertificate"] = inproxyTestConfig.brokerServerCertificate
  951. serverConfig["MeekServerPrivateKey"] = inproxyTestConfig.brokerServerPrivateKey
  952. serverConfig["MeekRequiredHeaders"] = inproxyTestConfig.brokerMeekRequiredHeaders
  953. serverConfig["InproxyBrokerSessionPrivateKey"] =
  954. inproxyTestConfig.brokerSessionPrivateKey
  955. serverConfig["InproxyBrokerObfuscationRootSecret"] =
  956. inproxyTestConfig.brokerObfuscationRootSecret
  957. serverConfig["InproxyBrokerServerEntrySignaturePublicKey"] =
  958. inproxyTestConfig.brokerServerEntrySignaturePublicKey
  959. serverConfig["InproxyBrokerAllowCommonASNMatching"] = true
  960. serverConfig["InproxyBrokerAllowBogonWebRTCConnections"] = true
  961. }
  962. // Uncomment to enable SIGUSR2 profile dumps
  963. //serverConfig["ProcessProfileOutputDirectory"] = "/tmp"
  964. serverConfigJSON, _ = json.Marshal(serverConfig)
  965. uniqueUserLog := make(chan map[string]interface{}, 1)
  966. domainBytesLog := make(chan map[string]interface{}, 1)
  967. serverTunnelLog := make(chan map[string]interface{}, 1)
  968. // Max 3 discovery logs:
  969. // 1. server startup
  970. // 2. hot reload of psinet db (runConfig.doHotReload)
  971. // 3. hot reload of server tactics (runConfig.doHotReload && doServerTactics)
  972. discoveryLog := make(chan map[string]interface{}, 3)
  973. serverLoadLog := make(chan map[string]interface{}, 1)
  974. inproxyProxyAnnounceLog := make(chan map[string]interface{}, 1)
  975. inproxyClientOfferLog := make(chan map[string]interface{}, 1)
  976. inproxyProxyAnswerLog := make(chan map[string]interface{}, 1)
  977. inproxyServerProxyQualityLog := make(chan map[string]interface{}, 1)
  978. setLogCallback(func(log []byte) {
  979. logFields := make(map[string]interface{})
  980. err := json.Unmarshal(log, &logFields)
  981. if err != nil {
  982. return
  983. }
  984. if logFields["event_name"] == nil {
  985. if logFields["discovery_strategy"] != nil {
  986. select {
  987. case discoveryLog <- logFields:
  988. default:
  989. }
  990. }
  991. return
  992. }
  993. switch logFields["event_name"].(string) {
  994. case "unique_user":
  995. select {
  996. case uniqueUserLog <- logFields:
  997. default:
  998. }
  999. case "domain_bytes":
  1000. select {
  1001. case domainBytesLog <- logFields:
  1002. default:
  1003. }
  1004. case "server_tunnel":
  1005. select {
  1006. case serverTunnelLog <- logFields:
  1007. default:
  1008. }
  1009. case "server_load":
  1010. select {
  1011. case serverLoadLog <- logFields:
  1012. default:
  1013. }
  1014. case "inproxy_broker":
  1015. event, ok := logFields["broker_event"].(string)
  1016. if !ok {
  1017. t.Errorf("missing inproxy_broker.broker_event")
  1018. }
  1019. switch event {
  1020. case "proxy-announce":
  1021. select {
  1022. case inproxyProxyAnnounceLog <- logFields:
  1023. default:
  1024. }
  1025. case "client-offer":
  1026. select {
  1027. case inproxyClientOfferLog <- logFields:
  1028. default:
  1029. }
  1030. case "proxy-answer":
  1031. select {
  1032. case inproxyProxyAnswerLog <- logFields:
  1033. default:
  1034. }
  1035. case "server-proxy-quality":
  1036. select {
  1037. case inproxyServerProxyQualityLog <- logFields:
  1038. default:
  1039. }
  1040. }
  1041. }
  1042. })
  1043. // run flow inspector if requested
  1044. var flowInspectorProxy *flowInspectorProxy
  1045. if runConfig.inspectFlows {
  1046. flowInspectorProxy, err = newFlowInspectorProxy()
  1047. if err != nil {
  1048. t.Fatalf("error starting flow inspector: %s", err)
  1049. }
  1050. flowInspectorProxy.start()
  1051. defer flowInspectorProxy.close()
  1052. }
  1053. // run server
  1054. serverWaitGroup := new(sync.WaitGroup)
  1055. serverWaitGroup.Add(1)
  1056. go func() {
  1057. defer serverWaitGroup.Done()
  1058. // Workaround for one-time logging initialization that persists across
  1059. // test runs. Reset logging to uninitialized. This assumes the
  1060. // previous run has completed and not left any dangling goroutines
  1061. // that may access these variables.
  1062. if log != nil {
  1063. log = nil
  1064. initLogging = sync.Once{}
  1065. }
  1066. err := RunServices(serverConfigJSON)
  1067. if err != nil {
  1068. // TODO: wrong goroutine for t.FatalNow()
  1069. t.Errorf("error running server: %s", err)
  1070. }
  1071. }()
  1072. stopServer := func() {
  1073. // Test: orderly server shutdown
  1074. p, _ := os.FindProcess(os.Getpid())
  1075. p.Signal(os.Interrupt)
  1076. shutdownTimeout := time.NewTimer(5 * time.Second)
  1077. shutdownOk := make(chan struct{}, 1)
  1078. go func() {
  1079. serverWaitGroup.Wait()
  1080. shutdownOk <- struct{}{}
  1081. }()
  1082. select {
  1083. case <-shutdownOk:
  1084. case <-shutdownTimeout.C:
  1085. t.Fatalf("server shutdown timeout exceeded")
  1086. }
  1087. }
  1088. // Stop server on early exits due to failure.
  1089. defer func() {
  1090. if stopServer != nil {
  1091. stopServer()
  1092. }
  1093. }()
  1094. // TODO: monitor logs for more robust wait-until-loaded. For example,
  1095. // especially with the race detector on, QUIC-OSSH tests can fail as the
  1096. // client sends its initial packet before the server is ready.
  1097. time.Sleep(1 * time.Second)
  1098. // Test: hot reload (of psinet and traffic rules)
  1099. if runConfig.doHotReload {
  1100. // Change discovery servers. Tests that discovery switches over to
  1101. // these new servers.
  1102. discoveryServers, err = newDiscoveryServers([]string{"3.3.3.3"})
  1103. if err != nil {
  1104. t.Fatalf("newDiscoveryServers failed: %s\n", err)
  1105. }
  1106. // Pave new config files with different random values.
  1107. sponsorID, expectedHomepageURL = pavePsinetDatabaseFile(
  1108. t, psinetFilename, "", runConfig.doDefaultSponsorID, true, psinetValidServerEntryTags, discoveryServers)
  1109. propagationChannelID = paveOSLConfigFile(t, oslConfigFilename)
  1110. paveTrafficRulesFile(
  1111. t,
  1112. trafficRulesFilename,
  1113. propagationChannelID,
  1114. accessType,
  1115. authorizationIDStr,
  1116. runConfig.requireAuthorization,
  1117. runConfig.denyTrafficRules,
  1118. livenessTestSize)
  1119. if doServerTactics {
  1120. // Pave new tactics file with different discovery strategy. Tests
  1121. // that discovery switches over to the new strategy.
  1122. paveTacticsConfigFile(
  1123. t,
  1124. tacticsConfigFilename,
  1125. tacticsRequestPublicKey,
  1126. tacticsRequestPrivateKey,
  1127. tacticsRequestObfuscatedKey,
  1128. tacticsTunnelProtocol,
  1129. propagationChannelID,
  1130. livenessTestSize,
  1131. runConfig.doBurstMonitor,
  1132. runConfig.doDestinationBytes,
  1133. runConfig.doLegacyDestinationBytes,
  1134. runConfig.applyPrefix,
  1135. runConfig.forceFragmenting,
  1136. "consistent",
  1137. inproxyTacticsParametersJSON,
  1138. runConfig.doRestrictInproxy)
  1139. }
  1140. p, _ := os.FindProcess(os.Getpid())
  1141. p.Signal(syscall.SIGUSR1)
  1142. // TODO: monitor logs for more robust wait-until-reloaded
  1143. time.Sleep(1 * time.Second)
  1144. // After reloading psinet, the new sponsorID/expectedHomepageURL
  1145. // should be active, as tested in the client "Homepage" notice
  1146. // handler below.
  1147. }
  1148. // Exercise server_load logging
  1149. p, _ := os.FindProcess(os.Getpid())
  1150. p.Signal(syscall.SIGUSR2)
  1151. timer := time.NewTimer(1 * time.Second)
  1152. select {
  1153. case <-serverLoadLog:
  1154. case <-timer.C:
  1155. t.Fatalf("missing server load log")
  1156. }
  1157. timer.Stop()
  1158. // configure client
  1159. values.SetSSHClientVersionsSpec(values.NewPickOneSpec(testSSHClientVersions))
  1160. values.SetUserAgentsSpec(values.NewPickOneSpec(testUserAgents))
  1161. // TODO: currently, TargetServerEntry only works with one tunnel
  1162. numTunnels := 1
  1163. localSOCKSProxyPort := 1081
  1164. localHTTPProxyPort := 8081
  1165. // Use a distinct suffix for network ID for each test run to ensure tactics
  1166. // from different runs don't apply; this is a workaround for the singleton
  1167. // datastore.
  1168. networkID := fmt.Sprintf("WIFI-%s", time.Now().String())
  1169. jsonNetworkID := fmt.Sprintf(`,"NetworkID" : "%s"`, networkID)
  1170. jsonLimitTLSProfiles := ""
  1171. if runConfig.tlsProfile != "" {
  1172. jsonLimitTLSProfiles = fmt.Sprintf(`,"LimitTLSProfiles" : ["%s"]`, runConfig.tlsProfile)
  1173. }
  1174. testClientFeaturesJSON, _ := json.Marshal(testClientFeatures)
  1175. clientTunnelProtocol := runConfig.tunnelProtocol
  1176. if runConfig.clientTunnelProtocol != "" {
  1177. clientTunnelProtocol = runConfig.clientTunnelProtocol
  1178. }
  1179. clientConfigJSON := fmt.Sprintf(`
  1180. {
  1181. "ClientVersion" : "%d",
  1182. "ClientPlatform" : "%s",
  1183. "ClientFeatures" : %s,
  1184. "SponsorId" : "0000000000000000",
  1185. "PropagationChannelId" : "0000000000000000",
  1186. "DeviceRegion" : "%s",
  1187. "DeviceLocation" : "%s",
  1188. "DisableRemoteServerListFetcher" : true,
  1189. "EstablishTunnelPausePeriodSeconds" : 1,
  1190. "ConnectionWorkerPoolSize" : %d,
  1191. "LimitTunnelProtocols" : ["%s"]
  1192. %s
  1193. %s
  1194. }`,
  1195. testClientVersion,
  1196. testClientPlatform,
  1197. string(testClientFeaturesJSON),
  1198. testDeviceRegion,
  1199. testDeviceLocation,
  1200. numTunnels,
  1201. clientTunnelProtocol,
  1202. jsonLimitTLSProfiles,
  1203. jsonNetworkID)
  1204. // Don't print initial config setup notices
  1205. psiphon.SetNoticeWriter(io.Discard)
  1206. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  1207. if err != nil {
  1208. t.Fatalf("error processing configuration file: %s", err)
  1209. }
  1210. clientConfig.DataRootDirectory = testDataDirName
  1211. if !runConfig.doDefaultSponsorID {
  1212. clientConfig.SponsorId = sponsorID
  1213. }
  1214. clientConfig.PropagationChannelId = propagationChannelID
  1215. clientConfig.TunnelPoolSize = numTunnels
  1216. clientConfig.TargetServerEntry = string(encodedServerEntry)
  1217. clientConfig.LocalSocksProxyPort = localSOCKSProxyPort
  1218. clientConfig.LocalHttpProxyPort = localHTTPProxyPort
  1219. clientConfig.EmitSLOKs = true
  1220. clientConfig.EmitServerAlerts = true
  1221. // Exercise the WaitForNetworkConnectivity wired-up code path.
  1222. clientConfig.NetworkConnectivityChecker = &networkConnectivityChecker{}
  1223. if runConfig.inspectFlows {
  1224. trueVal := true
  1225. clientConfig.UpstreamProxyURL = fmt.Sprintf("socks5://%s", flowInspectorProxy.listener.Addr())
  1226. clientConfig.UpstreamProxyAllowAllServerEntrySources = &trueVal
  1227. }
  1228. if runConfig.doSplitTunnel {
  1229. clientConfig.SplitTunnelOwnRegion = true
  1230. }
  1231. if !runConfig.omitAuthorization {
  1232. clientConfig.Authorizations = []string{clientAuthorization}
  1233. }
  1234. // When using TLS-OSSH the test expects the server to log the fields
  1235. // tls_ossh_sni_server_name and tls_ossh_transformed_host_name, which are
  1236. // only shipped by the client when the host name is transformed.
  1237. if protocol.TunnelProtocolUsesTLSOSSH(clientTunnelProtocol) {
  1238. transformHostNameProbability := 1.0
  1239. clientConfig.TransformHostNameProbability = &transformHostNameProbability
  1240. clientConfig.CustomHostNameRegexes = []string{testCustomHostNameRegex}
  1241. customHostNameProbability := 1.0
  1242. clientConfig.CustomHostNameProbability = &customHostNameProbability
  1243. clientConfig.CustomHostNameLimitProtocols = []string{clientTunnelProtocol}
  1244. }
  1245. if runConfig.doSteeringIP {
  1246. if runConfig.tunnelProtocol != protocol.TUNNEL_PROTOCOL_FRONTED_MEEK {
  1247. t.Fatalf("steering IP test requires FRONTED-MEEK-OSSH")
  1248. }
  1249. protocol.SetFrontedMeekHTTPDialPortNumber(psiphonServerPort)
  1250. // Note that in an actual fronting deployment, the steering IP header
  1251. // is added to the HTTP request by the CDN and any ingress steering
  1252. // IP header would be stripped to avoid spoofing. To facilitate this
  1253. // test case, we just have the client add the steering IP header as
  1254. // if it were the CDN.
  1255. headers := make(http.Header)
  1256. headers.Set("X-Psiphon-Steering-Ip", testSteeringIP)
  1257. clientConfig.MeekAdditionalHeaders = headers
  1258. }
  1259. if runConfig.useLegacyAPIEncoding {
  1260. clientConfig.TargetAPIEncoding = protocol.PSIPHON_API_ENCODING_JSON
  1261. }
  1262. if doInproxy {
  1263. // Limitation: can't exercise DisableTunnels = true since the client
  1264. // is a singleton and so the single instance must act as both a
  1265. // client and proxy. This self-proxy scheme also requires setting
  1266. // InproxySkipAwaitFullyConnected.
  1267. clientConfig.DisableTunnels = false
  1268. clientConfig.InproxyEnableProxy = true
  1269. clientConfig.InproxySkipAwaitFullyConnected = true
  1270. clientConfig.InproxyProxySessionPrivateKey = inproxyTestConfig.proxySessionPrivateKey
  1271. clientConfig.InproxyMaxClients = 1
  1272. clientConfig.InproxyLimitUpstreamBytesPerSecond = 0
  1273. clientConfig.InproxyLimitDownstreamBytesPerSecond = 0
  1274. clientConfig.ServerEntrySignaturePublicKey = inproxyTestConfig.brokerServerEntrySignaturePublicKey
  1275. if runConfig.doPersonalPairing {
  1276. psiphon.SetAllowOverlappingPersonalCompartmentIDs(true)
  1277. defer psiphon.SetAllowOverlappingPersonalCompartmentIDs(false)
  1278. clientConfig.InproxyClientPersonalCompartmentID = inproxyTestConfig.personalCompartmentID
  1279. clientConfig.InproxyProxyPersonalCompartmentID = inproxyTestConfig.personalCompartmentID
  1280. }
  1281. // Simulate a CDN adding required HTTP headers by injecting them at
  1282. // the client.
  1283. headers := make(http.Header)
  1284. for name, value := range inproxyTestConfig.brokerMeekRequiredHeaders {
  1285. headers.Add(name, value)
  1286. }
  1287. clientConfig.MeekAdditionalHeaders = headers
  1288. // Configure the CAs required to verify the broker TLS certificate.
  1289. clientConfig.TrustedCACertificatesFilename = filepath.Join(testDataDirName, "rootCAs")
  1290. err = ioutil.WriteFile(
  1291. clientConfig.TrustedCACertificatesFilename,
  1292. []byte(inproxyTestConfig.brokerServerCertificate),
  1293. 0600)
  1294. if err != nil {
  1295. t.Fatalf("WriteFile failed: %s", err)
  1296. }
  1297. }
  1298. err = clientConfig.Commit(false)
  1299. if err != nil {
  1300. t.Fatalf("error committing configuration file: %s", err)
  1301. }
  1302. if doClientTactics {
  1303. // Configure nonfunctional values that must be overridden by tactics.
  1304. applyParameters := make(map[string]interface{})
  1305. applyParameters[parameters.TunnelConnectTimeout] = "1s"
  1306. applyParameters[parameters.TunnelRateLimits] = common.RateLimits{WriteBytesPerSecond: 1}
  1307. err = clientConfig.SetParameters("", true, applyParameters)
  1308. if err != nil {
  1309. t.Fatalf("SetParameters failed: %s", err)
  1310. }
  1311. } else {
  1312. // Directly apply same parameters that would've come from tactics.
  1313. applyParameters := make(map[string]interface{})
  1314. if runConfig.applyPrefix {
  1315. if protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  1316. applyParameters[parameters.OSSHPrefixSpecs] = transforms.Specs{
  1317. "TEST": {{"", "\x00{200}"}},
  1318. }
  1319. applyParameters[parameters.OSSHPrefixScopedSpecNames] = transforms.ScopedSpecNames{
  1320. "": {"TEST"},
  1321. }
  1322. applyParameters[parameters.OSSHPrefixProbability] = 1.0
  1323. applyParameters[parameters.OSSHPrefixSplitMinDelay] = "10ms"
  1324. applyParameters[parameters.OSSHPrefixSplitMaxDelay] = "20ms"
  1325. applyParameters[parameters.OSSHPrefixEnableFragmentor] = runConfig.forceFragmenting
  1326. } else if protocol.TunnelProtocolUsesShadowsocks(runConfig.tunnelProtocol) {
  1327. applyParameters[parameters.ShadowsocksPrefixSpecs] = transforms.Specs{
  1328. "TEST": {{"", "\x00{16}"}},
  1329. }
  1330. applyParameters[parameters.ShadowsocksPrefixScopedSpecNames] = transforms.ScopedSpecNames{
  1331. "": {"TEST"},
  1332. }
  1333. applyParameters[parameters.ShadowsocksPrefixProbability] = 1.0
  1334. }
  1335. }
  1336. if runConfig.forceFragmenting {
  1337. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols{runConfig.tunnelProtocol}
  1338. applyParameters[parameters.FragmentorProbability] = 1.0
  1339. applyParameters[parameters.FragmentorMinTotalBytes] = 1000
  1340. applyParameters[parameters.FragmentorMaxTotalBytes] = 2000
  1341. applyParameters[parameters.FragmentorMinWriteBytes] = 1
  1342. applyParameters[parameters.FragmentorMaxWriteBytes] = 100
  1343. applyParameters[parameters.FragmentorMinDelay] = 1 * time.Millisecond
  1344. applyParameters[parameters.FragmentorMaxDelay] = 10 * time.Millisecond
  1345. }
  1346. if runConfig.forceLivenessTest {
  1347. applyParameters[parameters.InitialLivenessTest] = parameters.LivenessTestSpecs{
  1348. "": &parameters.LivenessTestSpec{
  1349. MinUpstreamBytes: livenessTestSize,
  1350. MaxUpstreamBytes: livenessTestSize,
  1351. MinDownstreamBytes: livenessTestSize,
  1352. MaxDownstreamBytes: livenessTestSize,
  1353. },
  1354. }
  1355. applyParameters[parameters.LivenessTest] = parameters.LivenessTestSpecs{
  1356. "": &parameters.LivenessTestSpec{
  1357. MinUpstreamBytes: livenessTestSize,
  1358. MaxUpstreamBytes: livenessTestSize,
  1359. MinDownstreamBytes: livenessTestSize,
  1360. MaxDownstreamBytes: livenessTestSize,
  1361. },
  1362. }
  1363. }
  1364. if runConfig.doPruneServerEntries {
  1365. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMin] = 1 * time.Millisecond
  1366. applyParameters[parameters.PsiphonAPIStatusRequestShortPeriodMax] = 1 * time.Millisecond
  1367. }
  1368. err = clientConfig.SetParameters("", true, applyParameters)
  1369. if err != nil {
  1370. t.Fatalf("SetParameters failed: %s", err)
  1371. }
  1372. }
  1373. // connect to server with client
  1374. err = psiphon.OpenDataStore(clientConfig)
  1375. if err != nil {
  1376. t.Fatalf("error initializing client datastore: %s", err)
  1377. }
  1378. defer psiphon.CloseDataStore()
  1379. // Test unique user counting cases.
  1380. var expectUniqueUser bool
  1381. switch lastConnectedUpdateCount % 3 {
  1382. case 0:
  1383. // Mock no last_connected.
  1384. psiphon.SetKeyValue("lastConnected", "")
  1385. expectUniqueUser = true
  1386. case 1:
  1387. // Mock previous day last_connected.
  1388. psiphon.SetKeyValue(
  1389. "lastConnected",
  1390. time.Now().UTC().AddDate(0, 0, -1).Truncate(1*time.Hour).Format(time.RFC3339))
  1391. expectUniqueUser = true
  1392. case 2:
  1393. // Leave previous last_connected.
  1394. expectUniqueUser = false
  1395. }
  1396. // Clear SLOKs from previous test runs.
  1397. psiphon.DeleteSLOKs()
  1398. // Store prune server entry test server entries and failed tunnel records.
  1399. storePruneServerEntriesTest(
  1400. t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1401. controller, err := psiphon.NewController(clientConfig)
  1402. if err != nil {
  1403. t.Fatalf("error creating client controller: %s", err)
  1404. }
  1405. connectedServer := make(chan struct{}, 1)
  1406. inproxyActivity := make(chan struct{}, 1)
  1407. tunnelsEstablished := make(chan struct{}, 1)
  1408. homepageReceived := make(chan struct{}, 1)
  1409. slokSeeded := make(chan struct{}, 1)
  1410. numPruneNotices := 0
  1411. pruneServerEntriesNoticesEmitted := make(chan struct{}, 1)
  1412. serverAlertDisallowedNoticesEmitted := make(chan struct{}, 1)
  1413. untunneledPortForward := make(chan struct{}, 1)
  1414. discardTunnel := make(chan struct{}, 1)
  1415. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  1416. func(notice []byte) {
  1417. noticeType, payload, err := psiphon.GetNotice(notice)
  1418. if err != nil {
  1419. return
  1420. }
  1421. printNotice := false
  1422. switch noticeType {
  1423. case "ConnectedServer":
  1424. // Check that client connected with the expected protocol.
  1425. protocol := payload["protocol"].(string)
  1426. if protocol != clientTunnelProtocol {
  1427. // TODO: wrong goroutine for t.FatalNow()
  1428. t.Errorf("unexpected protocol: %s", protocol)
  1429. }
  1430. sendNotificationReceived(connectedServer)
  1431. case "Tunnels":
  1432. count := int(payload["count"].(float64))
  1433. if count >= numTunnels {
  1434. sendNotificationReceived(tunnelsEstablished)
  1435. }
  1436. case "Homepage":
  1437. homepageURL := payload["url"].(string)
  1438. if homepageURL != expectedHomepageURL {
  1439. // TODO: wrong goroutine for t.FatalNow()
  1440. t.Errorf("unexpected homepage: %s", homepageURL)
  1441. }
  1442. sendNotificationReceived(homepageReceived)
  1443. case "SLOKSeeded":
  1444. sendNotificationReceived(slokSeeded)
  1445. case "PruneServerEntry":
  1446. numPruneNotices += 1
  1447. if numPruneNotices == expectedNumPruneNotices {
  1448. sendNotificationReceived(pruneServerEntriesNoticesEmitted)
  1449. }
  1450. case "ServerAlert":
  1451. reason := payload["reason"].(string)
  1452. actionURLsPayload := payload["actionURLs"].([]interface{})
  1453. actionURLs := make([]string, len(actionURLsPayload))
  1454. for i, value := range actionURLsPayload {
  1455. actionURLs[i] = value.(string)
  1456. }
  1457. if reason == protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC &&
  1458. reflect.DeepEqual(actionURLs, testDisallowedTrafficAlertActionURLs) {
  1459. sendNotificationReceived(serverAlertDisallowedNoticesEmitted)
  1460. }
  1461. case "Untunneled":
  1462. sendNotificationReceived(untunneledPortForward)
  1463. case "InproxyProxyTotalActivity":
  1464. // This assumes that both non-zero bytes up and down are
  1465. // reported in at least same notice, although there's some
  1466. // unlikely chance it's only one or the other.
  1467. connectedClients := int(payload["connectedClients"].(float64))
  1468. bytesUp := int(payload["totalBytesUp"].(float64))
  1469. bytesDown := int(payload["totalBytesDown"].(float64))
  1470. if connectedClients == 1 && bytesUp > 0 && bytesDown > 0 {
  1471. sendNotificationReceived(inproxyActivity)
  1472. }
  1473. case "Info":
  1474. if strings.Contains(payload["message"].(string), "discard tunnel") {
  1475. sendNotificationReceived(discardTunnel)
  1476. }
  1477. }
  1478. if printNotice {
  1479. fmt.Printf("%s\n", string(notice))
  1480. }
  1481. }))
  1482. ctx, cancelFunc := context.WithCancel(context.Background())
  1483. controllerWaitGroup := new(sync.WaitGroup)
  1484. controllerWaitGroup.Add(1)
  1485. go func() {
  1486. defer controllerWaitGroup.Done()
  1487. controller.Run(ctx)
  1488. }()
  1489. stopClient := func() {
  1490. cancelFunc()
  1491. shutdownTimeout := time.NewTimer(20 * time.Second)
  1492. shutdownOk := make(chan struct{}, 1)
  1493. go func() {
  1494. controllerWaitGroup.Wait()
  1495. shutdownOk <- struct{}{}
  1496. }()
  1497. select {
  1498. case <-shutdownOk:
  1499. case <-shutdownTimeout.C:
  1500. t.Errorf("controller shutdown timeout exceeded")
  1501. }
  1502. }
  1503. // Stop client on early exits due to failure.
  1504. defer func() {
  1505. if stopClient != nil {
  1506. stopClient()
  1507. }
  1508. }()
  1509. // Test: tunnels must be established, and correct homepage
  1510. // must be received, within 30 seconds
  1511. timeoutSignal := make(chan struct{})
  1512. go func() {
  1513. timer := time.NewTimer(30 * time.Second)
  1514. <-timer.C
  1515. close(timeoutSignal)
  1516. }()
  1517. expectDiscardTunnel := runConfig.doRestrictInproxy
  1518. if expectDiscardTunnel {
  1519. waitOnNotification(t, discardTunnel, timeoutSignal, "discard tunnel timeout exceeded")
  1520. return
  1521. } else {
  1522. waitOnNotification(t, connectedServer, timeoutSignal, "connected server timeout exceeded")
  1523. if doInproxy {
  1524. waitOnNotification(t, inproxyActivity, timeoutSignal, "inproxy activity timeout exceeded")
  1525. }
  1526. waitOnNotification(t, tunnelsEstablished, timeoutSignal, "tunnel established timeout exceeded")
  1527. waitOnNotification(t, homepageReceived, timeoutSignal, "homepage received timeout exceeded")
  1528. // The tunnel connected, so the local last_connected has been updated.
  1529. lastConnectedUpdateCount += 1
  1530. }
  1531. if runConfig.doChangeBytesConfig {
  1532. if !runConfig.doDestinationBytes || !runConfig.doLegacyDestinationBytes {
  1533. t.Fatalf("invalid test configuration")
  1534. }
  1535. // Test: now that the client is connected, change the domain bytes and
  1536. // destination bytes configurations. No stats should be logged, even
  1537. // with an already connected client.
  1538. // Pave psinet without domain bytes; retain the same sponsor ID. The
  1539. // random homepage URLs will change, but this has no effect on the
  1540. // already connected client.
  1541. _, _ = pavePsinetDatabaseFile(
  1542. t, psinetFilename, sponsorID, runConfig.doDefaultSponsorID, false, psinetValidServerEntryTags, discoveryServers)
  1543. // Pave tactics without destination bytes.
  1544. paveTacticsConfigFile(
  1545. t,
  1546. tacticsConfigFilename,
  1547. tacticsRequestPublicKey,
  1548. tacticsRequestPrivateKey,
  1549. tacticsRequestObfuscatedKey,
  1550. tacticsTunnelProtocol,
  1551. propagationChannelID,
  1552. livenessTestSize,
  1553. runConfig.doBurstMonitor,
  1554. false,
  1555. false,
  1556. runConfig.applyPrefix,
  1557. runConfig.forceFragmenting,
  1558. "consistent",
  1559. inproxyTacticsParametersJSON,
  1560. runConfig.doRestrictInproxy)
  1561. p, _ := os.FindProcess(os.Getpid())
  1562. p.Signal(syscall.SIGUSR1)
  1563. // TODO: monitor logs for more robust wait-until-reloaded
  1564. time.Sleep(1 * time.Second)
  1565. }
  1566. expectTrafficFailure := runConfig.denyTrafficRules || (runConfig.omitAuthorization && runConfig.requireAuthorization)
  1567. if runConfig.doTunneledWebRequest {
  1568. // Test: tunneled web site fetch
  1569. err = makeTunneledWebRequest(
  1570. t, localHTTPProxyPort, mockWebServerURL, true, mockWebServerExpectedResponse)
  1571. if err == nil {
  1572. if expectTrafficFailure {
  1573. t.Fatalf("unexpected tunneled web request success")
  1574. }
  1575. } else {
  1576. if !expectTrafficFailure {
  1577. t.Fatalf("tunneled web request failed: %s", err)
  1578. }
  1579. }
  1580. }
  1581. if runConfig.doTunneledDomainRequest && !expectTrafficFailure {
  1582. // Test: tunneled web site fetch exercising the handleTCPChannel DNS
  1583. // resolver and cache
  1584. err = makeTunneledWebRequest(
  1585. t, localHTTPProxyPort, "https://psiphon.ca", false, "")
  1586. if err != nil {
  1587. t.Fatalf("tunneled web request failed: %s", err)
  1588. }
  1589. // Establish a second port forward to the same domain. The DNS
  1590. // resolution is expected to be cached. This is checked below via the
  1591. // dns_count reported in the server_load log.
  1592. err = makeTunneledWebRequest(
  1593. t, localHTTPProxyPort, "https://psiphon.ca", false, "")
  1594. if err != nil {
  1595. t.Fatalf("tunneled web request failed: %s", err)
  1596. }
  1597. }
  1598. if runConfig.doTunneledNTPRequest {
  1599. // Test: tunneled UDP packets
  1600. udpgwServerAddress := serverConfig["UDPInterceptUdpgwServerAddress"].(string)
  1601. err = makeTunneledNTPRequest(t, localSOCKSProxyPort, udpgwServerAddress)
  1602. if err == nil {
  1603. if expectTrafficFailure {
  1604. t.Fatalf("unexpected tunneled NTP request success")
  1605. }
  1606. } else {
  1607. if !expectTrafficFailure {
  1608. t.Fatalf("tunneled NTP request failed: %s", err)
  1609. }
  1610. }
  1611. }
  1612. // Test: await SLOK payload or server alert notice
  1613. time.Sleep(1 * time.Second)
  1614. if !expectTrafficFailure {
  1615. waitOnNotification(t, slokSeeded, timeoutSignal, "SLOK seeded timeout exceeded")
  1616. numSLOKs := psiphon.CountSLOKs()
  1617. if numSLOKs != expectedNumSLOKs {
  1618. t.Fatalf("unexpected number of SLOKs: %d", numSLOKs)
  1619. }
  1620. } else {
  1621. // Note: in expectTrafficFailure case, timeoutSignal may have already fired.
  1622. waitOnNotification(t, serverAlertDisallowedNoticesEmitted, nil, "")
  1623. }
  1624. // Test: await expected prune server entry notices
  1625. //
  1626. // Note: will take up to PsiphonAPIStatusRequestShortPeriodMax to emit.
  1627. if expectedNumPruneNotices > 0 {
  1628. waitOnNotification(t, pruneServerEntriesNoticesEmitted, nil, "")
  1629. }
  1630. if runConfig.doDanglingTCPConn {
  1631. // Test: client that has established TCP connection but not completed
  1632. // any handshakes must not block/delay server shutdown
  1633. danglingConn, err := net.Dial(
  1634. "tcp", net.JoinHostPort(psiphonServerIPAddress, strconv.Itoa(psiphonServerPort)))
  1635. if err != nil {
  1636. t.Fatalf("TCP dial failed: %s", err)
  1637. }
  1638. defer danglingConn.Close()
  1639. }
  1640. // Test: check for split tunnel notice
  1641. if runConfig.doSplitTunnel {
  1642. if !runConfig.doTunneledWebRequest || expectTrafficFailure {
  1643. t.Fatalf("invalid test run configuration")
  1644. }
  1645. waitOnNotification(t, untunneledPortForward, nil, "")
  1646. } else {
  1647. // There should be no "Untunneled" notice. This check assumes that any
  1648. // unexpected Untunneled notice will have been delivered at this point,
  1649. // after the SLOK notice.
  1650. select {
  1651. case <-untunneledPortForward:
  1652. t.Fatalf("unexpected untunneled port forward")
  1653. default:
  1654. }
  1655. }
  1656. // Trigger server_load logging once more, to exercise
  1657. // sshClient.peakMetrics. As we don't have a reference to the server's
  1658. // Support struct, we can't invoke logServerLoad directly and there's a
  1659. // potential race between asynchronous logServerLoad invocation and
  1660. // client shutdown. For now, we sleep as a workaround.
  1661. p.Signal(syscall.SIGUSR2)
  1662. time.Sleep(1 * time.Second)
  1663. // Shutdown to ensure logs/notices are flushed
  1664. stopClient()
  1665. stopClient = nil
  1666. stopServer()
  1667. stopServer = nil
  1668. // Test: all expected server logs were emitted
  1669. // TODO: stops should be fully synchronous, but, intermittently,
  1670. // server_tunnel fails to appear ("missing server tunnel log")
  1671. // without this delay.
  1672. time.Sleep(100 * time.Millisecond)
  1673. // For in-proxy tunnel protocols, client BPF tactics are currently ignored and not applied by the 2nd hop.
  1674. expectClientBPFField := psiphon.ClientBPFEnabled() && doClientTactics && !protocol.TunnelProtocolUsesInproxy(runConfig.tunnelProtocol)
  1675. expectServerBPFField := ServerBPFEnabled() && protocol.TunnelProtocolIsDirect(runConfig.tunnelProtocol) && doServerTactics
  1676. expectServerPacketManipulationField := runConfig.doPacketManipulation
  1677. expectBurstFields := runConfig.doBurstMonitor
  1678. expectTCPPortForwardDial := (runConfig.doTunneledWebRequest || runConfig.doTunneledDomainRequest)
  1679. expectTCPDataTransfer := (runConfig.doTunneledWebRequest || runConfig.doTunneledDomainRequest) && !expectTrafficFailure && !runConfig.doSplitTunnel
  1680. expectDomainPortForward := runConfig.doTunneledDomainRequest
  1681. // Even with expectTrafficFailure, DNS port forwards will succeed
  1682. expectUDPDataTransfer := runConfig.doTunneledNTPRequest
  1683. expectQUICVersion := ""
  1684. if runConfig.limitQUICVersions {
  1685. expectQUICVersion = limitQUICVersions[0]
  1686. }
  1687. expectDestinationBytesFields := runConfig.doDestinationBytes && !runConfig.doChangeBytesConfig
  1688. expectLegacyDestinationBytesFields := runConfig.doLegacyDestinationBytes && !runConfig.doChangeBytesConfig
  1689. expectMeekHTTPVersion := ""
  1690. if protocol.TunnelProtocolUsesMeek(runConfig.tunnelProtocol) {
  1691. if protocol.TunnelProtocolUsesFrontedMeek(runConfig.tunnelProtocol) {
  1692. expectMeekHTTPVersion = "HTTP/2.0"
  1693. } else {
  1694. expectMeekHTTPVersion = "HTTP/1.1"
  1695. }
  1696. }
  1697. // The client still reports zero domain_bytes when no port forwards are
  1698. // allowed (expectTrafficFailure).
  1699. //
  1700. // Limitation: this check is disabled in the in-proxy case since, in the
  1701. // self-proxy scheme, the proxy shuts down before the client can send its
  1702. // final status request.
  1703. expectDomainBytes := !runConfig.doChangeBytesConfig && !doInproxy
  1704. select {
  1705. case logFields := <-serverTunnelLog:
  1706. err := checkExpectedServerTunnelLogFields(
  1707. runConfig,
  1708. propagationChannelID,
  1709. clientConfig.SponsorId,
  1710. doClientTactics,
  1711. expectClientBPFField,
  1712. expectServerBPFField,
  1713. expectServerPacketManipulationField,
  1714. expectBurstFields,
  1715. expectTCPPortForwardDial,
  1716. expectTCPDataTransfer,
  1717. expectUDPDataTransfer,
  1718. expectDomainPortForward,
  1719. expectQUICVersion,
  1720. expectDestinationBytesFields,
  1721. expectLegacyDestinationBytesFields,
  1722. passthroughAddress,
  1723. expectMeekHTTPVersion,
  1724. inproxyTestConfig,
  1725. logFields)
  1726. if err != nil {
  1727. t.Fatalf("invalid server tunnel log fields: %s", err)
  1728. }
  1729. default:
  1730. t.Fatalf("missing server tunnel log")
  1731. }
  1732. if expectUniqueUser {
  1733. select {
  1734. case logFields := <-uniqueUserLog:
  1735. err := checkExpectedUniqueUserLogFields(
  1736. runConfig,
  1737. logFields)
  1738. if err != nil {
  1739. t.Fatalf("invalid unique user log fields: %s", err)
  1740. }
  1741. default:
  1742. t.Fatalf("missing unique user log")
  1743. }
  1744. } else {
  1745. select {
  1746. case <-uniqueUserLog:
  1747. t.Fatalf("unexpected unique user log")
  1748. default:
  1749. }
  1750. }
  1751. if expectDomainBytes {
  1752. select {
  1753. case logFields := <-domainBytesLog:
  1754. err := checkExpectedDomainBytesLogFields(
  1755. runConfig,
  1756. logFields)
  1757. if err != nil {
  1758. t.Fatalf("invalid domain bytes log fields: %s", err)
  1759. }
  1760. default:
  1761. t.Fatalf("missing domain bytes log")
  1762. }
  1763. } else {
  1764. select {
  1765. case <-domainBytesLog:
  1766. t.Fatalf("unexpected domain bytes log")
  1767. default:
  1768. }
  1769. }
  1770. select {
  1771. case logFields := <-serverLoadLog:
  1772. if expectDomainPortForward {
  1773. dnsCount := int(logFields["dns_count"].(map[string]any)["ALL"].(float64))
  1774. if dnsCount != 1 {
  1775. t.Fatalf("unexpected dns_count: %d", dnsCount)
  1776. }
  1777. }
  1778. default:
  1779. t.Fatalf("missing server load log")
  1780. }
  1781. // Check logs emitted by discovery.
  1782. var expectedDiscoveryStrategy []string
  1783. // Discovery emits 1 log on startup.
  1784. if doServerTactics {
  1785. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "classic")
  1786. } else {
  1787. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "consistent")
  1788. }
  1789. if runConfig.doHotReload {
  1790. if doServerTactics {
  1791. // Discovery emits 1 log when tactics are reloaded, which happens
  1792. // before the psinet database is reloaded.
  1793. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "classic")
  1794. }
  1795. // Discovery emits 1 when the psinet database is reloaded.
  1796. expectedDiscoveryStrategy = append(expectedDiscoveryStrategy, "consistent")
  1797. }
  1798. for _, expectedStrategy := range expectedDiscoveryStrategy {
  1799. select {
  1800. case logFields := <-discoveryLog:
  1801. if strategy, ok := logFields["discovery_strategy"].(string); ok {
  1802. if strategy != expectedStrategy {
  1803. t.Fatalf("expected discovery strategy \"%s\"", expectedStrategy)
  1804. }
  1805. } else {
  1806. t.Fatalf("missing discovery_strategy field")
  1807. }
  1808. default:
  1809. t.Fatalf("missing discovery log")
  1810. }
  1811. }
  1812. // Check in-proxy broker logs. This check also confirms that the server
  1813. // proxy quality report request succeeded.
  1814. logChannels := []chan map[string]interface{}{
  1815. inproxyProxyAnnounceLog,
  1816. inproxyClientOfferLog,
  1817. inproxyProxyAnswerLog,
  1818. inproxyServerProxyQualityLog}
  1819. for _, logChannel := range logChannels {
  1820. // There's no proxy quality report in personal pairing mode.
  1821. expectLog := !(logChannel == inproxyServerProxyQualityLog && runConfig.doPersonalPairing)
  1822. if doInproxy && expectLog {
  1823. select {
  1824. case logFields := <-logChannel:
  1825. // Check that broker receives the correct fronting provider ID.
  1826. //
  1827. // TODO: check more fields
  1828. if logChannel == inproxyProxyAnnounceLog ||
  1829. logChannel == inproxyClientOfferLog ||
  1830. logChannel == inproxyServerProxyQualityLog {
  1831. fronting_provider_id, ok := logFields["fronting_provider_id"].(string)
  1832. if !ok || fronting_provider_id != inproxyTestConfig.brokerFrontingProviderID {
  1833. t.Errorf("unexpected inproxy_broker.fronting_provider_id")
  1834. }
  1835. }
  1836. default:
  1837. t.Fatalf("missing in-proxy broker log")
  1838. }
  1839. } else {
  1840. select {
  1841. case <-logChannel:
  1842. t.Fatalf("unexpected in-proxy broker log")
  1843. default:
  1844. }
  1845. }
  1846. }
  1847. // Check that datastore had retained/pruned server entries as expected.
  1848. checkPruneServerEntriesTest(t, runConfig, testDataDirName, pruneServerEntryTestCases)
  1849. // Inspect OSSH prefix flows, if applicable.
  1850. if runConfig.inspectFlows && runConfig.applyPrefix && protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  1851. flows := <-flowInspectorProxy.ch
  1852. serverFlows := flows[0]
  1853. clientFlows := flows[1]
  1854. expectedClientPrefix := bytes.Repeat([]byte{0x00}, 200)
  1855. expectedServerPrefix := bytes.Repeat([]byte{0x01}, 200)
  1856. if runConfig.forceFragmenting {
  1857. // Fragmentor was applied, so check for prefix in stream dump.
  1858. if !bytes.Equal(clientFlows.streamDump.Bytes()[:200], expectedClientPrefix) {
  1859. t.Fatal("client flow does not have expected prefix")
  1860. }
  1861. if !bytes.Equal(serverFlows.streamDump.Bytes()[:200], expectedServerPrefix) {
  1862. t.Fatal("server flow does not have expected prefix")
  1863. }
  1864. fragmentorMaxWriteBytes := 100
  1865. if len(clientFlows.flows[0].data) > fragmentorMaxWriteBytes {
  1866. t.Fatal("client flow was not fragmented")
  1867. }
  1868. if len(serverFlows.flows[0].data) > fragmentorMaxWriteBytes {
  1869. t.Fatal("server flow was not fragmented")
  1870. }
  1871. } else {
  1872. // Fragmentor was not applied, so check for prefix in first flow.
  1873. if !bytes.Equal(clientFlows.flows[0].data, expectedClientPrefix) {
  1874. t.Fatal("client flow does not have expected prefix")
  1875. }
  1876. if !bytes.Equal(serverFlows.flows[0].data, expectedServerPrefix) {
  1877. t.Fatal("server flow does not have expected prefix")
  1878. }
  1879. // Analyze time between prefix and next packet.
  1880. // client 10-20ms, 30-40ms for server with standard deviation of 2ms.
  1881. clientZtest := testSampleInUniformRange(clientFlows.flows[1].timeDelta.Microseconds(), 10000, 20000, 2000)
  1882. serverZtest := testSampleInUniformRange(serverFlows.flows[1].timeDelta.Microseconds(), 30000, 40000, 2000)
  1883. if !clientZtest {
  1884. t.Fatalf("client write delay after prefix too high: %f ms",
  1885. clientFlows.flows[1].timeDelta.Seconds()*1e3)
  1886. }
  1887. if !serverZtest {
  1888. t.Fatalf("server write delay after prefix too high: %f ms",
  1889. serverFlows.flows[1].timeDelta.Seconds()*1e3)
  1890. }
  1891. }
  1892. }
  1893. if runConfig.doSteeringIP {
  1894. // Access the unexported controller.steeringIPCache
  1895. controllerStruct := reflect.ValueOf(controller).Elem()
  1896. steeringIPCacheField := controllerStruct.FieldByName("steeringIPCache")
  1897. steeringIPCacheField = reflect.NewAt(
  1898. steeringIPCacheField.Type(), unsafe.Pointer(steeringIPCacheField.UnsafeAddr())).Elem()
  1899. steeringIPCache := steeringIPCacheField.Interface().(*lrucache.Cache)
  1900. if steeringIPCache.ItemCount() != 1 {
  1901. t.Fatalf("unexpected steering IP cache size: %d", steeringIPCache.ItemCount())
  1902. }
  1903. key := fmt.Sprintf(
  1904. "%s %s %s",
  1905. networkID,
  1906. generateConfigParams.FrontingProviderID,
  1907. runConfig.tunnelProtocol)
  1908. entry, ok := steeringIPCache.Get(key)
  1909. if !ok {
  1910. t.Fatalf("no entry for steering IP cache key: %s", key)
  1911. }
  1912. if entry.(string) != testSteeringIP {
  1913. t.Fatalf("unexpected cached steering IP: %v", entry)
  1914. }
  1915. }
  1916. // Check that the client discovered one of the discovery servers.
  1917. discoveredServers := make(map[string]*protocol.ServerEntry)
  1918. // Otherwise NewServerEntryIterator only returns TargetServerEntry.
  1919. clientConfig.TargetServerEntry = ""
  1920. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  1921. if err != nil {
  1922. t.Fatalf("NewServerEntryIterator failed: %s", err)
  1923. }
  1924. defer iterator.Close()
  1925. for {
  1926. serverEntry, err := iterator.Next()
  1927. if err != nil {
  1928. t.Fatalf("ServerIterator.Next failed: %s", err)
  1929. }
  1930. if serverEntry == nil {
  1931. break
  1932. }
  1933. discoveredServers[serverEntry.IpAddress] = serverEntry
  1934. }
  1935. foundOne := false
  1936. for _, server := range discoveryServers {
  1937. serverEntry, err := protocol.DecodeServerEntry(server.EncodedServerEntry, "", "")
  1938. if err != nil {
  1939. t.Fatalf("protocol.DecodeServerEntry failed: %s", err)
  1940. }
  1941. if v, ok := discoveredServers[serverEntry.IpAddress]; ok {
  1942. if v.Tag == serverEntry.Tag {
  1943. foundOne = true
  1944. break
  1945. }
  1946. }
  1947. }
  1948. if !foundOne {
  1949. t.Fatalf("expected client to discover at least one server")
  1950. }
  1951. }
  1952. func sendNotificationReceived(c chan<- struct{}) {
  1953. select {
  1954. case c <- struct{}{}:
  1955. default:
  1956. }
  1957. }
  1958. func waitOnNotification(t *testing.T, c, timeoutSignal <-chan struct{}, timeoutMessage string) {
  1959. if timeoutSignal == nil {
  1960. <-c
  1961. } else {
  1962. select {
  1963. case <-c:
  1964. case <-timeoutSignal:
  1965. t.Fatal(timeoutMessage)
  1966. }
  1967. }
  1968. }
  1969. type networkConnectivityChecker struct {
  1970. }
  1971. func (c *networkConnectivityChecker) HasNetworkConnectivity() int {
  1972. return 1
  1973. }
  1974. func checkExpectedServerTunnelLogFields(
  1975. runConfig *runServerConfig,
  1976. expectPropagationChannelID string,
  1977. expectSponsorID string,
  1978. expectAppliedTacticsTag bool,
  1979. expectClientBPFField bool,
  1980. expectServerBPFField bool,
  1981. expectServerPacketManipulationField bool,
  1982. expectBurstFields bool,
  1983. expectTCPPortForwardDial bool,
  1984. expectTCPDataTransfer bool,
  1985. expectUDPDataTransfer bool,
  1986. expectDomainPortForward bool,
  1987. expectQUICVersion string,
  1988. expectDestinationBytesFields bool,
  1989. expectLegacyDestinationBytesFields bool,
  1990. expectPassthroughAddress *string,
  1991. expectMeekHTTPVersion string,
  1992. inproxyTestConfig *inproxyTestConfig,
  1993. fields map[string]interface{}) error {
  1994. // Limitations:
  1995. //
  1996. // - client_build_rev not set in test build (see common/buildinfo.go)
  1997. // - egress_region, upstream_proxy_type, upstream_proxy_custom_header_names not exercised in test
  1998. // - fronting_provider_id/meek_dial_ip_address/meek_resolved_ip_address only logged for FRONTED meek protocols
  1999. for _, name := range []string{
  2000. "host_id",
  2001. "tunnel_id",
  2002. "start_time",
  2003. "duration",
  2004. "session_id",
  2005. "is_first_tunnel_in_session",
  2006. "last_connected",
  2007. "establishment_duration",
  2008. "propagation_channel_id",
  2009. "sponsor_id",
  2010. "client_version",
  2011. "client_platform",
  2012. "client_features",
  2013. "relay_protocol",
  2014. "device_region",
  2015. "device_location",
  2016. "ssh_client_version",
  2017. "server_entry_region",
  2018. "server_entry_source",
  2019. "server_entry_timestamp",
  2020. "dial_port_number",
  2021. "is_replay",
  2022. "dial_duration",
  2023. "candidate_number",
  2024. "established_tunnels_count",
  2025. "network_latency_multiplier",
  2026. "network_type",
  2027. // The test run ensures that logServerLoad is invoked while the client
  2028. // is connected, so the following must be logged.
  2029. "peak_concurrent_proximate_accepted_clients",
  2030. "peak_concurrent_proximate_established_clients",
  2031. } {
  2032. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2033. return fmt.Errorf("missing expected field '%s'", name)
  2034. }
  2035. }
  2036. appliedTacticsTag := len(fields[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME].(string)) > 0
  2037. if expectAppliedTacticsTag != appliedTacticsTag {
  2038. return fmt.Errorf("unexpected applied_tactics_tag")
  2039. }
  2040. if fields["host_id"].(string) != "example-host-id" {
  2041. return fmt.Errorf("unexpected host_id '%s'", fields["host_id"])
  2042. }
  2043. if fields["propagation_channel_id"].(string) != expectPropagationChannelID {
  2044. return fmt.Errorf("unexpected propagation_channel_id '%s'", fields["propagation_channel_id"])
  2045. }
  2046. if fields["sponsor_id"].(string) != expectSponsorID {
  2047. return fmt.Errorf("unexpected sponsor_id '%s'", fields["sponsor_id"])
  2048. }
  2049. if int(fields["client_version"].(float64)) != testClientVersion {
  2050. return fmt.Errorf("unexpected client_version '%s'", fields["client_version"])
  2051. }
  2052. if fields["client_platform"].(string) != testClientPlatform {
  2053. return fmt.Errorf("unexpected client_platform '%s'", fields["client_platform"])
  2054. }
  2055. clientFeatures := fields["client_features"].([]interface{})
  2056. if len(clientFeatures) != len(testClientFeatures) {
  2057. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  2058. }
  2059. for i, feature := range testClientFeatures {
  2060. if clientFeatures[i].(string) != feature {
  2061. return fmt.Errorf("unexpected client_features '%s'", fields["client_features"])
  2062. }
  2063. }
  2064. tunnelProtocol := runConfig.tunnelProtocol
  2065. if runConfig.clientTunnelProtocol != "" {
  2066. // In cases such as UNFRONTED-HTTPS-OSSH/TLS-OSSH demux,
  2067. // runConfig.tunnelProtocol is the server listening protocol and
  2068. // runConfig.clientTunnelProtocol is the actual tunnel protocol.
  2069. tunnelProtocol = runConfig.clientTunnelProtocol
  2070. }
  2071. if fields["relay_protocol"].(string) != tunnelProtocol {
  2072. return fmt.Errorf("unexpected relay_protocol '%s'", fields["relay_protocol"])
  2073. }
  2074. if !common.Contains(testSSHClientVersions, fields["ssh_client_version"].(string)) {
  2075. return fmt.Errorf("unexpected ssh_client_version '%s'", fields["ssh_client_version"])
  2076. }
  2077. if fields["network_type"].(string) != testNetworkType {
  2078. return fmt.Errorf("unexpected network_type '%s'", fields["network_type"])
  2079. }
  2080. // With interruptions, timeouts, and retries in some tests, there may be
  2081. // more than one dangling accepted_client.
  2082. peakConcurrentProximateAcceptedClients :=
  2083. int(fields["peak_concurrent_proximate_accepted_clients"].(float64))
  2084. if peakConcurrentProximateAcceptedClients < 0 ||
  2085. peakConcurrentProximateAcceptedClients > 10 {
  2086. return fmt.Errorf(
  2087. "unexpected peak_concurrent_proximate_accepted_clients '%v'",
  2088. fields["peak_concurrent_proximate_accepted_clients"])
  2089. }
  2090. peakConcurrentProximateEstablishedClients :=
  2091. int(fields["peak_concurrent_proximate_established_clients"].(float64))
  2092. if peakConcurrentProximateEstablishedClients != 0 {
  2093. return fmt.Errorf(
  2094. "unexpected peak_concurrent_proximate_established_clients '%v'",
  2095. fields["peak_concurrent_proximate_established_clients"])
  2096. }
  2097. // In some negative test cases, no port forwards are attempted, in which
  2098. // case these fields are not logged.
  2099. if expectTCPDataTransfer {
  2100. if fields["peak_tcp_port_forward_failure_rate"] == nil {
  2101. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate'")
  2102. }
  2103. if fields["peak_tcp_port_forward_failure_rate"].(float64) != 0.0 {
  2104. return fmt.Errorf(
  2105. "unexpected peak_tcp_port_forward_failure_rate '%v'",
  2106. fields["peak_tcp_port_forward_failure_rate"])
  2107. }
  2108. if fields["peak_tcp_port_forward_failure_rate_sample_size"] == nil {
  2109. return fmt.Errorf("missing expected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  2110. }
  2111. if fields["peak_tcp_port_forward_failure_rate_sample_size"].(float64) <= 0.0 {
  2112. return fmt.Errorf(
  2113. "unexpected peak_tcp_port_forward_failure_rate_sample_size '%v'",
  2114. fields["peak_tcp_port_forward_failure_rate_sample_size"])
  2115. }
  2116. } else {
  2117. if fields["peak_tcp_port_forward_failure_rate"] != nil {
  2118. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate'")
  2119. }
  2120. if fields["peak_tcp_port_forward_failure_rate_sample_size"] != nil {
  2121. return fmt.Errorf("unexpected field 'peak_tcp_port_forward_failure_rate_sample_size'")
  2122. }
  2123. }
  2124. if expectUDPDataTransfer || expectDomainPortForward {
  2125. if fields["peak_dns_failure_rate"] == nil {
  2126. return fmt.Errorf("missing expected field 'peak_dns_failure_rate'")
  2127. }
  2128. if fields["peak_dns_failure_rate"].(float64) != 0.0 {
  2129. return fmt.Errorf(
  2130. "unexpected peak_dns_failure_rate '%v'", fields["peak_dns_failure_rate"])
  2131. }
  2132. if fields["peak_dns_failure_rate_sample_size"] == nil {
  2133. return fmt.Errorf("missing expected field 'peak_dns_failure_rate_sample_size'")
  2134. }
  2135. if fields["peak_dns_failure_rate_sample_size"].(float64) <= 0.0 {
  2136. return fmt.Errorf(
  2137. "unexpected peak_dns_failure_rate_sample_size '%v'",
  2138. fields["peak_dns_failure_rate_sample_size"])
  2139. }
  2140. } else {
  2141. if fields["peak_dns_failure_rate"] != nil {
  2142. return fmt.Errorf("unexpected field 'peak_dns_failure_rate'")
  2143. }
  2144. if fields["peak_dns_failure_rate_sample_size"] != nil {
  2145. return fmt.Errorf("unexpected field 'peak_dns_failure_rate_sample_size'")
  2146. }
  2147. }
  2148. // TODO: the following cases should check that fields are not logged when
  2149. // not expected.
  2150. if runConfig.doSplitTunnel {
  2151. if fields["split_tunnel"] == nil {
  2152. return fmt.Errorf("missing expected field 'split_tunnel'")
  2153. }
  2154. if fields["split_tunnel"].(bool) != true {
  2155. return fmt.Errorf("missing split_tunnel value")
  2156. }
  2157. }
  2158. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  2159. for _, name := range []string{
  2160. "padding",
  2161. "pad_response",
  2162. } {
  2163. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2164. return fmt.Errorf("missing expected field '%s'", name)
  2165. }
  2166. }
  2167. }
  2168. if protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  2169. for _, name := range []string{
  2170. "user_agent",
  2171. "meek_transformed_host_name",
  2172. "meek_cookie_size",
  2173. "meek_limit_request",
  2174. "meek_underlying_connection_count",
  2175. "meek_server_http_version",
  2176. } {
  2177. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2178. return fmt.Errorf("missing expected field '%s'", name)
  2179. }
  2180. }
  2181. if !common.Contains(testUserAgents, fields["user_agent"].(string)) {
  2182. return fmt.Errorf("unexpected user_agent '%s'", fields["user_agent"])
  2183. }
  2184. if fields["meek_server_http_version"].(string) != expectMeekHTTPVersion {
  2185. return fmt.Errorf("unexpected meek_server_http_version '%s'", fields["meek_server_http_version"])
  2186. }
  2187. }
  2188. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) {
  2189. for _, name := range []string{
  2190. "meek_host_header",
  2191. } {
  2192. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2193. return fmt.Errorf("missing expected field '%s'", name)
  2194. }
  2195. }
  2196. hostName := fields["meek_host_header"].(string)
  2197. dialPortNumber := int(fields["dial_port_number"].(float64))
  2198. if dialPortNumber != 80 {
  2199. hostName, _, _ = net.SplitHostPort(hostName)
  2200. }
  2201. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2202. return fmt.Errorf("unexpected meek_host_header '%s'", fields["meek_host_header"])
  2203. }
  2204. if !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  2205. for _, name := range []string{
  2206. "meek_dial_ip_address",
  2207. "meek_resolved_ip_address",
  2208. } {
  2209. if fields[name] != nil {
  2210. return fmt.Errorf("unexpected field '%s'", name)
  2211. }
  2212. }
  2213. }
  2214. }
  2215. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  2216. for _, name := range []string{
  2217. "meek_tls_padding",
  2218. "meek_sni_server_name",
  2219. } {
  2220. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2221. return fmt.Errorf("missing expected field '%s'", name)
  2222. }
  2223. }
  2224. hostName := fields["meek_sni_server_name"].(string)
  2225. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2226. return fmt.Errorf("unexpected meek_sni_server_name '%s'", fields["meek_sni_server_name"])
  2227. }
  2228. if !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  2229. for _, name := range []string{
  2230. "meek_dial_ip_address",
  2231. "meek_resolved_ip_address",
  2232. "meek_host_header",
  2233. } {
  2234. if fields[name] != nil {
  2235. return fmt.Errorf("unexpected field '%s'", name)
  2236. }
  2237. }
  2238. }
  2239. }
  2240. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) ||
  2241. protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  2242. for _, name := range []string{
  2243. "tls_profile",
  2244. "tls_version",
  2245. "tls_sent_ticket",
  2246. "tls_did_resume",
  2247. } {
  2248. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2249. return fmt.Errorf("missing expected field '%s'", name)
  2250. }
  2251. }
  2252. if !common.Contains(protocol.SupportedTLSProfiles, fields["tls_profile"].(string)) {
  2253. return fmt.Errorf("unexpected tls_profile '%s'", fields["tls_profile"])
  2254. }
  2255. tlsVersion := fields["tls_version"].(string)
  2256. if !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_12) &&
  2257. !strings.HasPrefix(tlsVersion, protocol.TLS_VERSION_13) {
  2258. return fmt.Errorf("unexpected tls_version '%s'", fields["tls_version"])
  2259. }
  2260. }
  2261. if protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  2262. for _, name := range []string{
  2263. "tls_padding",
  2264. "tls_ossh_sni_server_name",
  2265. "tls_ossh_transformed_host_name",
  2266. } {
  2267. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2268. return fmt.Errorf("missing expected field '%s'", name)
  2269. }
  2270. }
  2271. hostName := fields["tls_ossh_sni_server_name"].(string)
  2272. if regexp.MustCompile(testCustomHostNameRegex).FindString(hostName) != hostName {
  2273. return fmt.Errorf("unexpected tls_ossh_sni_server_name '%s'", fields["tls_ossh_sni_server_name"])
  2274. }
  2275. }
  2276. if protocol.TunnelProtocolUsesQUIC(tunnelProtocol) {
  2277. for _, name := range []string{
  2278. "quic_version",
  2279. "quic_dial_sni_address",
  2280. "quic_dial_early",
  2281. "quic_sent_ticket",
  2282. "quic_did_resume",
  2283. "quic_obfuscated_psk",
  2284. } {
  2285. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2286. return fmt.Errorf("missing expected field '%s'", name)
  2287. }
  2288. }
  2289. quicVersion := fields["quic_version"].(string)
  2290. if !common.Contains(protocol.SupportedQUICVersions, quicVersion) ||
  2291. (runConfig.limitQUICVersions && quicVersion != expectQUICVersion) {
  2292. return fmt.Errorf("unexpected quic_version '%s'", fields["quic_version"])
  2293. }
  2294. }
  2295. if protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  2296. for _, name := range []string{
  2297. // Fields sent by the broker and populated via
  2298. // inproxy.ServerBrokerSessions.HandlePacket
  2299. "inproxy_broker_id",
  2300. "inproxy_connection_id",
  2301. "inproxy_proxy_id",
  2302. "inproxy_matched_common_compartments",
  2303. "inproxy_client_nat_type",
  2304. "inproxy_proxy_propagation_channel_id",
  2305. "inproxy_proxy_sponsor_id",
  2306. "inproxy_proxy_client_version",
  2307. "inproxy_proxy_client_platform",
  2308. "inproxy_proxy_client_features",
  2309. "inproxy_proxy_device_region",
  2310. "inproxy_proxy_device_location",
  2311. "inproxy_proxy_network_type",
  2312. "inproxy_proxy_protocol_version",
  2313. "inproxy_proxy_nat_type",
  2314. "inproxy_proxy_max_clients",
  2315. "inproxy_proxy_connecting_clients",
  2316. "inproxy_proxy_connected_clients",
  2317. "inproxy_proxy_limit_upstream_bytes_per_second",
  2318. "inproxy_proxy_limit_downstream_bytes_per_second",
  2319. "inproxy_proxy_peak_upstream_bytes_per_second",
  2320. "inproxy_proxy_peak_downstream_bytes_per_second",
  2321. "inproxy_proxy_is_priority",
  2322. // These ProxyMetrics fields are not populated in this test:
  2323. // "inproxy_proxy_client_build_rev",
  2324. // "inproxy_proxy_port_mapping_types",
  2325. // Fields sent by the client
  2326. "inproxy_broker_is_replay",
  2327. "inproxy_broker_is_reuse",
  2328. "inproxy_broker_transport",
  2329. "inproxy_broker_fronting_provider_id",
  2330. "inproxy_broker_dial_address",
  2331. "inproxy_broker_resolved_ip_address",
  2332. "inproxy_webrtc_randomize_dtls",
  2333. "inproxy_webrtc_use_media_streams",
  2334. "inproxy_webrtc_padded_messages_sent",
  2335. "inproxy_webrtc_padded_messages_received",
  2336. "inproxy_webrtc_decoy_messages_sent",
  2337. "inproxy_webrtc_decoy_messages_received",
  2338. "inproxy_dial_webrtc_ice_gathering_duration",
  2339. "inproxy_dial_broker_offer_duration",
  2340. "inproxy_dial_webrtc_connection_duration",
  2341. } {
  2342. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2343. return fmt.Errorf("missing expected field '%s'", name)
  2344. }
  2345. }
  2346. if fields["inproxy_broker_id"].(string) != inproxyTestConfig.brokerSessionPublicKeyCurve25519 {
  2347. return fmt.Errorf("unexpected inproxy_broker_id '%s'", fields["inproxy_broker_id"])
  2348. }
  2349. if fields["inproxy_proxy_id"].(string) != inproxyTestConfig.proxySessionPublicKeyCurve25519 {
  2350. return fmt.Errorf("unexpected inproxy_proxy_id '%s'", fields["inproxy_proxy_id"])
  2351. }
  2352. if fields["inproxy_matched_common_compartments"].(bool) != !runConfig.doPersonalPairing {
  2353. return fmt.Errorf("unexpected inproxy_matched_common_compartments '%s'", fields["inproxy_matched_common_compartments"])
  2354. }
  2355. if fields["inproxy_broker_fronting_provider_id"].(string) != inproxyTestConfig.brokerFrontingProviderID {
  2356. return fmt.Errorf("unexpected inproxy_broker_fronting_provider_id '%s'", fields["inproxy_broker_fronting_provider_id"])
  2357. }
  2358. // Check some fields from ProxyMetrics. Since the proxy and client are
  2359. // the same tunnel core instance, fields such as session_id are the
  2360. // same for both the client and the proxy.
  2361. if fields["inproxy_proxy_session_id"].(string) != fields["session_id"].(string) {
  2362. return fmt.Errorf("unexpected inproxy_proxy_session_id '%s'", fields["session_id"])
  2363. }
  2364. if fields["inproxy_proxy_propagation_channel_id"].(string) != expectPropagationChannelID {
  2365. return fmt.Errorf("unexpected inproxy_proxy_propagation_channel_id '%s'", fields["inproxy_proxy_propagation_channel_id"])
  2366. }
  2367. if fields["inproxy_proxy_sponsor_id"].(string) != expectSponsorID {
  2368. return fmt.Errorf("unexpected inproxy_proxy_sponsor_id '%s'", fields["inproxy_proxy_sponsor_id"])
  2369. }
  2370. if int(fields["inproxy_proxy_client_version"].(float64)) != testClientVersion {
  2371. return fmt.Errorf("unexpected inproxy_proxy_client_version '%s'", fields["inproxy_proxy_client_version"])
  2372. }
  2373. if fields["inproxy_proxy_client_platform"].(string) != testClientPlatform {
  2374. return fmt.Errorf("unexpected inproxy_proxy_client_platform '%s'", fields["inproxy_proxy_client_platform"])
  2375. }
  2376. clientFeatures := fields["inproxy_proxy_client_features"].([]interface{})
  2377. if len(clientFeatures) != len(testClientFeatures) {
  2378. return fmt.Errorf("unexpected inproxy_proxy_client_features '%s'", fields["inproxy_proxy_client_features"])
  2379. }
  2380. for i, feature := range testClientFeatures {
  2381. if clientFeatures[i].(string) != feature {
  2382. return fmt.Errorf("unexpected inproxy_proxy_client_features '%s'", fields["inproxy_proxy_client_features"])
  2383. }
  2384. }
  2385. if fields["inproxy_proxy_device_region"].(string) != testDeviceRegion {
  2386. return fmt.Errorf("unexpected inproxy_proxy_device_region '%s'", fields["inproxy_proxy_device_region"])
  2387. }
  2388. if fields["inproxy_proxy_device_location"].(string) != testDeviceLocation {
  2389. return fmt.Errorf("unexpected inproxy_proxy_device_location '%s'", fields["inproxy_proxy_device_location"])
  2390. }
  2391. if fields["inproxy_proxy_network_type"].(string) != testNetworkType {
  2392. return fmt.Errorf("unexpected inproxy_proxy_network_type '%s'", fields["inproxy_proxy_network_type"])
  2393. }
  2394. if fields["inproxy_webrtc_use_media_streams"].(bool) != runConfig.useInproxyMediaStreams {
  2395. return fmt.Errorf("unexpected inproxy_webrtc_use_media_streams '%v'", fields["inproxy_webrtc_use_media_streams"])
  2396. }
  2397. }
  2398. if runConfig.applyPrefix {
  2399. if protocol.TunnelProtocolIsObfuscatedSSH(runConfig.tunnelProtocol) {
  2400. if fields["ossh_prefix"] == nil || fmt.Sprintf("%s", fields["ossh_prefix"]) == "" {
  2401. return fmt.Errorf("missing expected field 'ossh_prefix'")
  2402. }
  2403. } else if protocol.TunnelProtocolUsesShadowsocks(runConfig.tunnelProtocol) {
  2404. if fields["shadowsocks_prefix"] == nil || fmt.Sprintf("%s", fields["shadowsocks_prefix"]) == "" {
  2405. return fmt.Errorf("missing expected field 'shadowsocks_prefix'")
  2406. }
  2407. }
  2408. }
  2409. if runConfig.forceFragmenting {
  2410. for _, name := range []string{
  2411. "upstream_bytes_fragmented",
  2412. "upstream_min_bytes_written",
  2413. "upstream_max_bytes_written",
  2414. "upstream_min_delayed",
  2415. "upstream_max_delayed",
  2416. } {
  2417. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2418. return fmt.Errorf("missing expected field '%s'", name)
  2419. }
  2420. }
  2421. }
  2422. if expectClientBPFField {
  2423. name := "client_bpf"
  2424. if fields[name] == nil {
  2425. return fmt.Errorf("missing expected field '%s'", name)
  2426. } else if fmt.Sprintf("%s", fields[name]) != "test-client-bpf" {
  2427. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2428. }
  2429. }
  2430. if expectServerBPFField {
  2431. name := "server_bpf"
  2432. if fields[name] == nil {
  2433. return fmt.Errorf("missing expected field '%s'", name)
  2434. } else if fmt.Sprintf("%s", fields[name]) != "test-server-bpf" {
  2435. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2436. }
  2437. }
  2438. if expectServerPacketManipulationField {
  2439. name := "server_packet_manipulation"
  2440. if fields[name] == nil {
  2441. return fmt.Errorf("missing expected field '%s'", name)
  2442. } else if fmt.Sprintf("%s", fields[name]) != "test-packetman-spec" {
  2443. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2444. }
  2445. }
  2446. if expectBurstFields {
  2447. // common.TestBurstMonitoredConn covers inclusion of additional fields.
  2448. for _, name := range []string{
  2449. "burst_upstream_first_rate",
  2450. "burst_upstream_last_rate",
  2451. "burst_upstream_min_rate",
  2452. "burst_upstream_max_rate",
  2453. "burst_downstream_first_rate",
  2454. "burst_downstream_last_rate",
  2455. "burst_downstream_min_rate",
  2456. "burst_downstream_max_rate",
  2457. } {
  2458. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2459. return fmt.Errorf("missing expected field '%s'", name)
  2460. }
  2461. }
  2462. }
  2463. var checkTCPMetric func(float64) bool
  2464. if expectTCPPortForwardDial {
  2465. checkTCPMetric = func(f float64) bool { return f > 0 }
  2466. } else {
  2467. checkTCPMetric = func(f float64) bool { return f == 0 }
  2468. }
  2469. for _, name := range []string{
  2470. "peak_concurrent_dialing_port_forward_count_tcp",
  2471. } {
  2472. if fields[name] == nil {
  2473. return fmt.Errorf("missing expected field '%s'", name)
  2474. }
  2475. if !checkTCPMetric(fields[name].(float64)) {
  2476. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  2477. }
  2478. }
  2479. if expectTCPDataTransfer {
  2480. checkTCPMetric = func(f float64) bool { return f > 0 }
  2481. } else {
  2482. checkTCPMetric = func(f float64) bool { return f == 0 }
  2483. }
  2484. for _, name := range []string{
  2485. "bytes_up_tcp",
  2486. "bytes_down_tcp",
  2487. "peak_concurrent_port_forward_count_tcp",
  2488. "total_port_forward_count_tcp",
  2489. } {
  2490. if fields[name] == nil {
  2491. return fmt.Errorf("missing expected field '%s'", name)
  2492. }
  2493. if !checkTCPMetric(fields[name].(float64)) {
  2494. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  2495. }
  2496. }
  2497. var checkUDPMetric func(float64) bool
  2498. if expectUDPDataTransfer {
  2499. checkUDPMetric = func(f float64) bool { return f > 0 }
  2500. } else {
  2501. checkUDPMetric = func(f float64) bool { return f == 0 }
  2502. }
  2503. for _, name := range []string{
  2504. "bytes_up_udp",
  2505. "bytes_down_udp",
  2506. "peak_concurrent_port_forward_count_udp",
  2507. "total_port_forward_count_udp",
  2508. "total_udpgw_channel_count",
  2509. } {
  2510. if fields[name] == nil {
  2511. return fmt.Errorf("missing expected field '%s'", name)
  2512. }
  2513. if !checkUDPMetric(fields[name].(float64)) {
  2514. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  2515. }
  2516. }
  2517. for _, name := range []string{
  2518. "asn_dest_bytes",
  2519. "asn_dest_bytes_up_tcp",
  2520. "asn_dest_bytes_down_tcp",
  2521. "asn_dest_bytes_up_udp",
  2522. "asn_dest_bytes_down_udp",
  2523. } {
  2524. if expectDestinationBytesFields && fields[name] == nil {
  2525. return fmt.Errorf("missing expected field '%s'", name)
  2526. } else if !expectDestinationBytesFields && fields[name] != nil {
  2527. return fmt.Errorf("unexpected field '%s'", name)
  2528. }
  2529. }
  2530. if expectDestinationBytesFields {
  2531. for _, pair := range [][]string{
  2532. {"asn_dest_bytes", "bytes"},
  2533. {"asn_dest_bytes_up_tcp", "bytes_up_tcp"},
  2534. {"asn_dest_bytes_down_tcp", "bytes_down_tcp"},
  2535. {"asn_dest_bytes_up_udp", "bytes_up_udp"},
  2536. {"asn_dest_bytes_down_udp", "bytes_down_udp"},
  2537. } {
  2538. if _, ok := fields[pair[0]].(map[string]any)[testGeoIPASN].(float64); !ok {
  2539. return fmt.Errorf("missing field entry %s: '%v'", pair[0], testGeoIPASN)
  2540. }
  2541. value0 := int64(fields[pair[0]].(map[string]any)[testGeoIPASN].(float64))
  2542. value1 := int64(fields[pair[1]].(float64))
  2543. ok := value0 == value1
  2544. if pair[0] == "asn_dest_bytes_up_udp" || pair[0] == "asn_dest_bytes_down_udp" || pair[0] == "asn_dest_bytes" {
  2545. // DNS requests are excluded from destination bytes counting
  2546. ok = value0 > 0 && value0 < value1
  2547. }
  2548. if !ok {
  2549. return fmt.Errorf("unexpected field value %s: %v != %v", pair[0], fields[pair[0]], fields[pair[1]])
  2550. }
  2551. }
  2552. }
  2553. for _, name := range []string{
  2554. "dest_bytes_asn",
  2555. "dest_bytes_up_tcp",
  2556. "dest_bytes_down_tcp",
  2557. "dest_bytes_up_udp",
  2558. "dest_bytes_down_udp",
  2559. "dest_bytes",
  2560. } {
  2561. if expectLegacyDestinationBytesFields && fields[name] == nil {
  2562. return fmt.Errorf("missing expected field '%s'", name)
  2563. } else if !expectLegacyDestinationBytesFields && fields[name] != nil {
  2564. return fmt.Errorf("unexpected field '%s'", name)
  2565. }
  2566. }
  2567. if expectLegacyDestinationBytesFields {
  2568. name := "dest_bytes_asn"
  2569. if fields[name].(string) != testGeoIPASN {
  2570. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  2571. }
  2572. for _, pair := range [][]string{
  2573. {"dest_bytes_up_tcp", "bytes_up_tcp"},
  2574. {"dest_bytes_down_tcp", "bytes_down_tcp"},
  2575. {"dest_bytes_up_udp", "bytes_up_udp"},
  2576. {"dest_bytes_down_udp", "bytes_down_udp"},
  2577. {"dest_bytes", "bytes"},
  2578. } {
  2579. value0 := int64(fields[pair[0]].(float64))
  2580. value1 := int64(fields[pair[1]].(float64))
  2581. ok := value0 == value1
  2582. if pair[0] == "dest_bytes_up_udp" || pair[0] == "dest_bytes_down_udp" || pair[0] == "dest_bytes" {
  2583. // DNS requests are excluded from destination bytes counting
  2584. ok = value0 > 0 && value0 < value1
  2585. }
  2586. if !ok {
  2587. return fmt.Errorf("unexpected field value %s: %v != %v", pair[0], fields[pair[0]], fields[pair[1]])
  2588. }
  2589. }
  2590. }
  2591. if expectPassthroughAddress != nil {
  2592. name := "passthrough_address"
  2593. if fields[name] == nil {
  2594. return fmt.Errorf("missing expected field '%s'", name)
  2595. }
  2596. if fields[name] != *expectPassthroughAddress {
  2597. return fmt.Errorf("unexpected field value %s: %v != %v", name, fields[name], *expectPassthroughAddress)
  2598. }
  2599. }
  2600. if runConfig.doLogHostProvider {
  2601. name := "provider"
  2602. if fields[name] == nil {
  2603. return fmt.Errorf("missing expected field '%s'", name)
  2604. } else if fmt.Sprintf("%s", fields[name]) != "example-host-provider" {
  2605. return fmt.Errorf("unexpected field value %s: '%s'", name, fields[name])
  2606. }
  2607. } else {
  2608. name := "provider"
  2609. if fields[name] != nil {
  2610. return fmt.Errorf("unexpected field '%s'", name)
  2611. }
  2612. }
  2613. if runConfig.doSteeringIP {
  2614. name := "relayed_steering_ip"
  2615. if fields[name] == nil {
  2616. return fmt.Errorf("missing expected field '%s'", name)
  2617. }
  2618. if fields[name] != testSteeringIP {
  2619. return fmt.Errorf("unexpected field value %s: %v != %v", name, fields[name], testSteeringIP)
  2620. }
  2621. name = "steering_ip"
  2622. if fields[name] != nil {
  2623. return fmt.Errorf("unexpected field '%s'", name)
  2624. }
  2625. }
  2626. return nil
  2627. }
  2628. func checkExpectedUniqueUserLogFields(
  2629. runConfig *runServerConfig,
  2630. fields map[string]interface{}) error {
  2631. for _, name := range []string{
  2632. "session_id",
  2633. "last_connected",
  2634. "propagation_channel_id",
  2635. "sponsor_id",
  2636. "client_platform",
  2637. "device_region",
  2638. "device_location",
  2639. } {
  2640. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2641. return fmt.Errorf("missing expected field '%s'", name)
  2642. }
  2643. }
  2644. return nil
  2645. }
  2646. func checkExpectedDomainBytesLogFields(
  2647. runConfig *runServerConfig,
  2648. fields map[string]interface{}) error {
  2649. for _, name := range []string{
  2650. "session_id",
  2651. "propagation_channel_id",
  2652. "sponsor_id",
  2653. "client_platform",
  2654. "device_region",
  2655. "device_location",
  2656. "domain",
  2657. "bytes",
  2658. } {
  2659. if fields[name] == nil || fmt.Sprintf("%s", fields[name]) == "" {
  2660. return fmt.Errorf("missing expected field '%s'", name)
  2661. }
  2662. if name == "domain" {
  2663. if fields[name].(string) != "ALL" && fields[name].(string) != "(OTHER)" {
  2664. return fmt.Errorf("unexpected field value %s: '%v'", name, fields[name])
  2665. }
  2666. }
  2667. }
  2668. return nil
  2669. }
  2670. func makeTunneledWebRequest(
  2671. t *testing.T,
  2672. localHTTPProxyPort int,
  2673. requestURL string,
  2674. checkResponseBody bool,
  2675. expectedResponseBody string) error {
  2676. roundTripTimeout := 30 * time.Second
  2677. proxyUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", localHTTPProxyPort))
  2678. if err != nil {
  2679. return fmt.Errorf("error initializing proxied HTTP request: %s", err)
  2680. }
  2681. httpClient := &http.Client{
  2682. Transport: &http.Transport{
  2683. Proxy: http.ProxyURL(proxyUrl),
  2684. },
  2685. Timeout: roundTripTimeout,
  2686. }
  2687. response, err := httpClient.Get(requestURL)
  2688. if err != nil {
  2689. return fmt.Errorf("error sending proxied HTTP request: %s", err)
  2690. }
  2691. body, err := ioutil.ReadAll(response.Body)
  2692. if err != nil {
  2693. return fmt.Errorf("error reading proxied HTTP response: %s", err)
  2694. }
  2695. response.Body.Close()
  2696. if checkResponseBody && string(body) != expectedResponseBody {
  2697. return fmt.Errorf("unexpected proxied HTTP response")
  2698. }
  2699. return nil
  2700. }
  2701. func makeTunneledNTPRequest(t *testing.T, localSOCKSProxyPort int, udpgwServerAddress string) error {
  2702. timeout := 20 * time.Second
  2703. var err error
  2704. testHostnames := []string{"time.google.com", "time.nist.gov", "pool.ntp.org"}
  2705. indexes := prng.Perm(len(testHostnames))
  2706. for _, index := range indexes {
  2707. testHostname := testHostnames[index]
  2708. err = makeTunneledNTPRequestAttempt(t, testHostname, timeout, localSOCKSProxyPort, udpgwServerAddress)
  2709. if err == nil {
  2710. break
  2711. }
  2712. t.Logf("makeTunneledNTPRequestAttempt failed: %s", err)
  2713. }
  2714. return err
  2715. }
  2716. var nextUDPProxyPort = 7300
  2717. func makeTunneledNTPRequestAttempt(
  2718. t *testing.T, testHostname string, timeout time.Duration, localSOCKSProxyPort int, udpgwServerAddress string) error {
  2719. nextUDPProxyPort++
  2720. localUDPProxyAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", nextUDPProxyPort))
  2721. if err != nil {
  2722. return fmt.Errorf("ResolveUDPAddr failed: %s", err)
  2723. }
  2724. // Note: this proxy is intended for this test only -- it only accepts a single connection,
  2725. // handles it, and then terminates.
  2726. localUDPProxy := func(destinationIP net.IP, destinationPort uint16, waitGroup *sync.WaitGroup) {
  2727. if waitGroup != nil {
  2728. defer waitGroup.Done()
  2729. }
  2730. destination := net.JoinHostPort(destinationIP.String(), strconv.Itoa(int(destinationPort)))
  2731. serverUDPConn, err := net.ListenUDP("udp", localUDPProxyAddress)
  2732. if err != nil {
  2733. t.Logf("ListenUDP for %s failed: %s", destination, err)
  2734. return
  2735. }
  2736. defer serverUDPConn.Close()
  2737. udpgwPreambleSize := 11 // see writeUdpgwPreamble
  2738. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  2739. packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
  2740. buffer[udpgwPreambleSize:])
  2741. if err != nil {
  2742. t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
  2743. return
  2744. }
  2745. socksProxyAddress := fmt.Sprintf("127.0.0.1:%d", localSOCKSProxyPort)
  2746. dialer, err := proxy.SOCKS5("tcp", socksProxyAddress, nil, proxy.Direct)
  2747. if err != nil {
  2748. t.Logf("proxy.SOCKS5 for %s failed: %s", destination, err)
  2749. return
  2750. }
  2751. socksTCPConn, err := dialer.Dial("tcp", udpgwServerAddress)
  2752. if err != nil {
  2753. t.Logf("dialer.Dial for %s failed: %s", destination, err)
  2754. return
  2755. }
  2756. defer socksTCPConn.Close()
  2757. flags := uint8(0)
  2758. if destinationPort == 53 {
  2759. flags = udpgwProtocolFlagDNS
  2760. }
  2761. err = writeUdpgwPreamble(
  2762. udpgwPreambleSize,
  2763. flags,
  2764. 0,
  2765. destinationIP,
  2766. destinationPort,
  2767. uint16(packetSize),
  2768. buffer)
  2769. if err != nil {
  2770. t.Logf("writeUdpgwPreamble for %s failed: %s", destination, err)
  2771. return
  2772. }
  2773. _, err = socksTCPConn.Write(buffer[0 : udpgwPreambleSize+packetSize])
  2774. if err != nil {
  2775. t.Logf("socksTCPConn.Write for %s failed: %s", destination, err)
  2776. return
  2777. }
  2778. udpgwProtocolMessage, err := readUdpgwMessage(socksTCPConn, buffer)
  2779. if err != nil {
  2780. t.Logf("readUdpgwMessage for %s failed: %s", destination, err)
  2781. return
  2782. }
  2783. _, err = serverUDPConn.WriteToUDP(udpgwProtocolMessage.packet, clientAddr)
  2784. if err != nil {
  2785. t.Logf("serverUDPConn.Write for %s failed: %s", destination, err)
  2786. return
  2787. }
  2788. }
  2789. // Tunneled DNS request
  2790. waitGroup := new(sync.WaitGroup)
  2791. waitGroup.Add(1)
  2792. go localUDPProxy(
  2793. net.IP(make([]byte, 4)), // ignored due to transparent DNS forwarding
  2794. 53,
  2795. waitGroup)
  2796. // TODO: properly synchronize with local UDP proxy startup
  2797. time.Sleep(1 * time.Second)
  2798. clientUDPConn, err := net.DialUDP("udp", nil, localUDPProxyAddress)
  2799. if err != nil {
  2800. return fmt.Errorf("DialUDP failed: %s", err)
  2801. }
  2802. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  2803. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  2804. addrs, err := resolveIP(testHostname, clientUDPConn)
  2805. clientUDPConn.Close()
  2806. if err == nil && (len(addrs) == 0 || len(addrs[0]) < 4) {
  2807. err = std_errors.New("no address")
  2808. }
  2809. if err != nil {
  2810. return fmt.Errorf("resolveIP failed: %s", err)
  2811. }
  2812. waitGroup.Wait()
  2813. // Tunneled NTP request
  2814. waitGroup = new(sync.WaitGroup)
  2815. waitGroup.Add(1)
  2816. go localUDPProxy(
  2817. addrs[0][len(addrs[0])-4:],
  2818. 123,
  2819. waitGroup)
  2820. // TODO: properly synchronize with local UDP proxy startup
  2821. time.Sleep(1 * time.Second)
  2822. clientUDPConn, err = net.DialUDP("udp", nil, localUDPProxyAddress)
  2823. if err != nil {
  2824. return fmt.Errorf("DialUDP failed: %s", err)
  2825. }
  2826. clientUDPConn.SetReadDeadline(time.Now().Add(timeout))
  2827. clientUDPConn.SetWriteDeadline(time.Now().Add(timeout))
  2828. // NTP protocol code from: https://groups.google.com/d/msg/golang-nuts/FlcdMU5fkLQ/CAeoD9eqm-IJ
  2829. ntpData := make([]byte, 48)
  2830. ntpData[0] = 3<<3 | 3
  2831. _, err = clientUDPConn.Write(ntpData)
  2832. if err != nil {
  2833. clientUDPConn.Close()
  2834. return fmt.Errorf("NTP Write failed: %s", err)
  2835. }
  2836. _, err = clientUDPConn.Read(ntpData)
  2837. if err != nil {
  2838. clientUDPConn.Close()
  2839. return fmt.Errorf("NTP Read failed: %s", err)
  2840. }
  2841. clientUDPConn.Close()
  2842. var sec, frac uint64
  2843. sec = uint64(ntpData[43]) | uint64(ntpData[42])<<8 | uint64(ntpData[41])<<16 | uint64(ntpData[40])<<24
  2844. frac = uint64(ntpData[47]) | uint64(ntpData[46])<<8 | uint64(ntpData[45])<<16 | uint64(ntpData[44])<<24
  2845. nsec := sec * 1e9
  2846. nsec += (frac * 1e9) >> 32
  2847. ntpNow := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec)).Local()
  2848. now := time.Now()
  2849. diff := ntpNow.Sub(now)
  2850. if diff < 0 {
  2851. diff = -diff
  2852. }
  2853. if diff > 1*time.Minute {
  2854. return fmt.Errorf("Unexpected NTP time: %s; local time: %s", ntpNow, now)
  2855. }
  2856. waitGroup.Wait()
  2857. return nil
  2858. }
  2859. func resolveIP(host string, conn net.Conn) (addrs []net.IP, err error) {
  2860. // Send the DNS query (A record only)
  2861. dnsConn := &dns.Conn{Conn: conn}
  2862. defer dnsConn.Close()
  2863. query := new(dns.Msg)
  2864. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  2865. query.RecursionDesired = true
  2866. dnsConn.WriteMsg(query)
  2867. // Process the response
  2868. response, err := dnsConn.ReadMsg()
  2869. if err == nil && response.MsgHdr.Id != query.MsgHdr.Id {
  2870. err = dns.ErrId
  2871. }
  2872. if err != nil {
  2873. return nil, errors.Trace(err)
  2874. }
  2875. addrs = make([]net.IP, 0)
  2876. for _, answer := range response.Answer {
  2877. if a, ok := answer.(*dns.A); ok {
  2878. addrs = append(addrs, a.A)
  2879. }
  2880. }
  2881. return addrs, nil
  2882. }
  2883. func pavePsinetDatabaseFile(
  2884. t *testing.T,
  2885. psinetFilename string,
  2886. sponsorID string,
  2887. useDefaultSponsorID bool,
  2888. doDomainBytes bool,
  2889. validServerEntryTags []string,
  2890. discoveryServers []*psinet.DiscoveryServer) (string, string) {
  2891. if sponsorID == "" {
  2892. sponsorID = strings.ToUpper(prng.HexString(8))
  2893. }
  2894. defaultSponsorID := ""
  2895. if useDefaultSponsorID {
  2896. defaultSponsorID = sponsorID
  2897. }
  2898. fakeDomain := prng.HexString(4)
  2899. fakePath := prng.HexString(4)
  2900. expectedHomepageURL := fmt.Sprintf("https://%s.com/%s", fakeDomain, fakePath)
  2901. discoverServersJSON, err := json.Marshal(discoveryServers)
  2902. if err != nil {
  2903. t.Fatalf("json.Marshal failed: %s\n", err)
  2904. }
  2905. psinetJSONFormat := `
  2906. {
  2907. "default_sponsor_id" : "%s",
  2908. "sponsors" : {
  2909. "%s" : {
  2910. %s
  2911. "home_pages" : {
  2912. "None" : [
  2913. {
  2914. "region" : null,
  2915. "url" : "%s"
  2916. }
  2917. ]
  2918. }
  2919. }
  2920. },
  2921. "default_alert_action_urls" : {
  2922. "%s" : %s
  2923. },
  2924. "valid_server_entry_tags" : {
  2925. %s
  2926. },
  2927. "discovery_servers" : %s
  2928. }
  2929. `
  2930. domainBytes := ""
  2931. if doDomainBytes {
  2932. domainBytes = `
  2933. "https_request_regexes" : [
  2934. {
  2935. "regex" : ".*",
  2936. "replace" : "ALL"
  2937. }
  2938. ],
  2939. `
  2940. }
  2941. actionURLsJSON, _ := json.Marshal(testDisallowedTrafficAlertActionURLs)
  2942. validServerEntryTagsJSON := ""
  2943. for _, serverEntryTag := range validServerEntryTags {
  2944. if len(validServerEntryTagsJSON) > 0 {
  2945. validServerEntryTagsJSON += ", "
  2946. }
  2947. validServerEntryTagsJSON += fmt.Sprintf("\"%s\" : true", serverEntryTag)
  2948. }
  2949. psinetJSON := fmt.Sprintf(
  2950. psinetJSONFormat,
  2951. defaultSponsorID,
  2952. sponsorID,
  2953. domainBytes,
  2954. expectedHomepageURL,
  2955. protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC,
  2956. actionURLsJSON,
  2957. validServerEntryTagsJSON,
  2958. discoverServersJSON)
  2959. err = ioutil.WriteFile(psinetFilename, []byte(psinetJSON), 0600)
  2960. if err != nil {
  2961. t.Fatalf("error paving psinet database file: %s", err)
  2962. }
  2963. return sponsorID, expectedHomepageURL
  2964. }
  2965. func paveTrafficRulesFile(
  2966. t *testing.T,
  2967. trafficRulesFilename string,
  2968. propagationChannelID string,
  2969. accessType string,
  2970. authorizationID string,
  2971. requireAuthorization bool,
  2972. deny bool,
  2973. livenessTestSize int) {
  2974. // Test both default and fast lookups
  2975. if intLookupThreshold != 10 {
  2976. t.Fatalf("unexpected intLookupThreshold")
  2977. }
  2978. TCPPorts := fmt.Sprintf("443, %s", mockWebServerPort)
  2979. UDPPorts := "53, 123, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010"
  2980. allowTCPPorts := TCPPorts
  2981. allowUDPPorts := UDPPorts
  2982. disallowTCPPorts := "1"
  2983. disallowUDPPorts := "1"
  2984. if deny {
  2985. allowTCPPorts = "1"
  2986. allowUDPPorts = "1"
  2987. disallowTCPPorts = TCPPorts
  2988. disallowUDPPorts = UDPPorts
  2989. }
  2990. authorizationFilterFormat := `,
  2991. "AuthorizedAccessTypes" : ["%s"],
  2992. "ActiveAuthorizationIDs" : ["%s"]
  2993. `
  2994. authorizationFilter := ""
  2995. if requireAuthorization {
  2996. authorizationFilter = fmt.Sprintf(
  2997. authorizationFilterFormat, accessType, authorizationID)
  2998. }
  2999. // Supports two traffic rule test cases:
  3000. //
  3001. // 1. no ports are allowed until after the filtered rule is applied
  3002. // 2. no required ports are allowed (deny = true)
  3003. trafficRulesJSONFormat := `
  3004. {
  3005. "DefaultRules" : {
  3006. "RateLimits" : {
  3007. "ReadBytesPerSecond": 16384,
  3008. "WriteBytesPerSecond": 16384,
  3009. "ReadUnthrottledBytes": %d,
  3010. "WriteUnthrottledBytes": %d
  3011. },
  3012. "AllowTCPPorts" : [1],
  3013. "AllowUDPPorts" : [1],
  3014. "MeekRateLimiterHistorySize" : 10,
  3015. "MeekRateLimiterThresholdSeconds" : 1,
  3016. "MeekRateLimiterGarbageCollectionTriggerCount" : 1,
  3017. "MeekRateLimiterReapHistoryFrequencySeconds" : 1,
  3018. "MeekRateLimiterRegions" : []
  3019. },
  3020. "FilteredRules" : [
  3021. {
  3022. "Filter" : {
  3023. "HandshakeParameters" : {
  3024. "propagation_channel_id" : ["%s"]
  3025. }%s
  3026. },
  3027. "Rules" : {
  3028. "RateLimits" : {
  3029. "ReadBytesPerSecond": 2097152,
  3030. "WriteBytesPerSecond": 2097152
  3031. },
  3032. "AllowTCPPorts" : [%s],
  3033. "AllowUDPPorts" : [%s],
  3034. "DisallowTCPPorts" : [%s],
  3035. "DisallowUDPPorts" : [%s]
  3036. }
  3037. }
  3038. ]
  3039. }
  3040. `
  3041. trafficRulesJSON := fmt.Sprintf(
  3042. trafficRulesJSONFormat,
  3043. livenessTestSize, livenessTestSize,
  3044. propagationChannelID, authorizationFilter,
  3045. allowTCPPorts, allowUDPPorts, disallowTCPPorts, disallowUDPPorts)
  3046. err := ioutil.WriteFile(trafficRulesFilename, []byte(trafficRulesJSON), 0600)
  3047. if err != nil {
  3048. t.Fatalf("error paving traffic rules file: %s", err)
  3049. }
  3050. }
  3051. var expectedNumSLOKs = 3
  3052. func paveOSLConfigFile(t *testing.T, oslConfigFilename string) string {
  3053. oslConfigJSONFormat := `
  3054. {
  3055. "Schemes" : [
  3056. {
  3057. "Epoch" : "%s",
  3058. "Regions" : [],
  3059. "PropagationChannelIDs" : ["%s"],
  3060. "MasterKey" : "wFuSbqU/pJ/35vRmoM8T9ys1PgDa8uzJps1Y+FNKa5U=",
  3061. "SeedSpecs" : [
  3062. {
  3063. "ID" : "IXHWfVgWFkEKvgqsjmnJuN3FpaGuCzQMETya+DSQvsk=",
  3064. "UpstreamSubnets" : ["0.0.0.0/0"],
  3065. "Targets" :
  3066. {
  3067. "BytesRead" : 1,
  3068. "BytesWritten" : 1,
  3069. "PortForwardDurationNanoseconds" : 1
  3070. }
  3071. },
  3072. {
  3073. "ID" : "qvpIcORLE2Pi5TZmqRtVkEp+OKov0MhfsYPLNV7FYtI=",
  3074. "UpstreamSubnets" : ["0.0.0.0/0"],
  3075. "Targets" :
  3076. {
  3077. "BytesRead" : 1,
  3078. "BytesWritten" : 1,
  3079. "PortForwardDurationNanoseconds" : 1
  3080. }
  3081. }
  3082. ],
  3083. "SeedSpecThreshold" : 2,
  3084. "SeedPeriodNanoseconds" : 2592000000000000,
  3085. "SeedPeriodKeySplits": [
  3086. {
  3087. "Total": 2,
  3088. "Threshold": 2
  3089. }
  3090. ]
  3091. },
  3092. {
  3093. "Epoch" : "%s",
  3094. "Regions" : [],
  3095. "PropagationChannelIDs" : ["%s"],
  3096. "MasterKey" : "HDc/mvd7e+lKDJD0fMpJW66YJ/VW4iqDRjeclEsMnro=",
  3097. "SeedSpecs" : [
  3098. {
  3099. "ID" : "/M0vsT0IjzmI0MvTI9IYe8OVyeQGeaPZN2xGxfLw/UQ=",
  3100. "UpstreamSubnets" : ["0.0.0.0/0"],
  3101. "Targets" :
  3102. {
  3103. "BytesRead" : 1,
  3104. "BytesWritten" : 1,
  3105. "PortForwardDurationNanoseconds" : 1
  3106. }
  3107. }
  3108. ],
  3109. "SeedSpecThreshold" : 1,
  3110. "SeedPeriodNanoseconds" : 2592000000000000,
  3111. "SeedPeriodKeySplits": [
  3112. {
  3113. "Total": 1,
  3114. "Threshold": 1
  3115. }
  3116. ]
  3117. }
  3118. ]
  3119. }
  3120. `
  3121. propagationChannelID := strings.ToUpper(prng.HexString(8))
  3122. now := time.Now().UTC()
  3123. epoch := now.Truncate(720 * time.Hour)
  3124. epochStr := epoch.Format(time.RFC3339Nano)
  3125. oslConfigJSON := fmt.Sprintf(
  3126. oslConfigJSONFormat,
  3127. epochStr, propagationChannelID,
  3128. epochStr, propagationChannelID)
  3129. err := ioutil.WriteFile(oslConfigFilename, []byte(oslConfigJSON), 0600)
  3130. if err != nil {
  3131. t.Fatalf("error paving osl config file: %s", err)
  3132. }
  3133. return propagationChannelID
  3134. }
  3135. func paveTacticsConfigFile(
  3136. t *testing.T,
  3137. tacticsConfigFilename string,
  3138. tacticsRequestPublicKey string,
  3139. tacticsRequestPrivateKey string,
  3140. tacticsRequestObfuscatedKey string,
  3141. tunnelProtocol string,
  3142. propagationChannelID string,
  3143. livenessTestSize int,
  3144. doBurstMonitor bool,
  3145. doDestinationBytes bool,
  3146. doLegacyDestinationBytes bool,
  3147. applyOsshPrefix bool,
  3148. enableOsshPrefixFragmenting bool,
  3149. discoveryStategy string,
  3150. inproxyParametersJSON string,
  3151. doRestrictAllInproxyProviderRegions bool) {
  3152. // Setting LimitTunnelProtocols passively exercises the
  3153. // server-side LimitTunnelProtocols enforcement.
  3154. tacticsConfigJSONFormat := `
  3155. {
  3156. "RequestPublicKey" : "%s",
  3157. "RequestPrivateKey" : "%s",
  3158. "RequestObfuscatedKey" : "%s",
  3159. "DefaultTactics" : {
  3160. "TTL" : "60s",
  3161. "Probability" : 1.0,
  3162. "Parameters" : {
  3163. %s
  3164. %s
  3165. %s
  3166. %s
  3167. %s
  3168. %s
  3169. "LimitTunnelProtocols" : ["%s"],
  3170. "FragmentorLimitProtocols" : ["%s"],
  3171. "FragmentorProbability" : 1.0,
  3172. "FragmentorMinTotalBytes" : 1000,
  3173. "FragmentorMaxTotalBytes" : 2000,
  3174. "FragmentorMinWriteBytes" : 1,
  3175. "FragmentorMaxWriteBytes" : 100,
  3176. "FragmentorMinDelay" : "1ms",
  3177. "FragmentorMaxDelay" : "10ms",
  3178. "FragmentorDownstreamLimitProtocols" : ["%s"],
  3179. "FragmentorDownstreamProbability" : 1.0,
  3180. "FragmentorDownstreamMinTotalBytes" : 1000,
  3181. "FragmentorDownstreamMaxTotalBytes" : 2000,
  3182. "FragmentorDownstreamMinWriteBytes" : 1,
  3183. "FragmentorDownstreamMaxWriteBytes" : 100,
  3184. "FragmentorDownstreamMinDelay" : "1ms",
  3185. "FragmentorDownstreamMaxDelay" : "10ms",
  3186. "LivenessTestMinUpstreamBytes" : %d,
  3187. "LivenessTestMaxUpstreamBytes" : %d,
  3188. "LivenessTestMinDownstreamBytes" : %d,
  3189. "LivenessTestMaxDownstreamBytes" : %d,
  3190. "BPFServerTCPProgram": {
  3191. "Name" : "test-server-bpf",
  3192. "Instructions" : [
  3193. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  3194. "BPFServerTCPProbability" : 1.0,
  3195. "BPFClientTCPProgram": {
  3196. "Name" : "test-client-bpf",
  3197. "Instructions" : [
  3198. {"Op": "RetConstant", "Args": {"Val": 65535}}]},
  3199. "BPFClientTCPProbability" : 1.0,
  3200. "ServerPacketManipulationSpecs" : [{"Name": "test-packetman-spec", "PacketSpecs": [["TCP-flags S"]]}],
  3201. "ServerPacketManipulationProbability" : 1.0,
  3202. "ServerProtocolPacketManipulations": {"All" : ["test-packetman-spec"]},
  3203. "ServerDiscoveryStrategy": "%s"
  3204. }
  3205. },
  3206. "FilteredTactics" : [
  3207. {
  3208. "Filter" : {
  3209. "APIParameters" : {"propagation_channel_id" : ["%s"]},
  3210. "SpeedTestRTTMilliseconds" : {
  3211. "Aggregation" : "Median",
  3212. "AtLeast" : 1
  3213. }
  3214. },
  3215. "Tactics" : {
  3216. "Parameters" : {
  3217. "TunnelConnectTimeout" : "20s",
  3218. "TunnelRateLimits" : {"WriteBytesPerSecond": 1000000},
  3219. "TransformHostNameProbability" : 1.0,
  3220. "PickUserAgentProbability" : 1.0,
  3221. "ApplicationParameters" : {
  3222. "AppFlag1" : true,
  3223. "AppConfig1" : {"Option1" : "A", "Option2" : "B"},
  3224. "AppSwitches1" : [1, 2, 3, 4]
  3225. },
  3226. "CustomHostNameRegexes": ["%s"],
  3227. "CustomHostNameProbability": 1.0,
  3228. "CustomHostNameLimitProtocols": ["%s"]
  3229. }
  3230. }
  3231. }
  3232. ]
  3233. }
  3234. `
  3235. burstParameters := ""
  3236. if doBurstMonitor {
  3237. burstParameters = `
  3238. "ServerBurstUpstreamDeadline" : "100ms",
  3239. "ServerBurstUpstreamTargetBytes" : 1000,
  3240. "ServerBurstDownstreamDeadline" : "100ms",
  3241. "ServerBurstDownstreamTargetBytes" : 100000,
  3242. "ClientBurstUpstreamDeadline" : "100ms",
  3243. "ClientBurstUpstreamTargetBytes" : 1000,
  3244. "ClientBurstDownstreamDeadline" : "100ms",
  3245. "ClientBurstDownstreamTargetBytes" : 100000,
  3246. `
  3247. }
  3248. destinationBytesParameters := ""
  3249. if doDestinationBytes {
  3250. destinationBytesParameters = fmt.Sprintf(`
  3251. "DestinationBytesMetricsASNs" : ["%s"],
  3252. `, testGeoIPASN)
  3253. }
  3254. legacyDestinationBytesParameters := ""
  3255. if doLegacyDestinationBytes {
  3256. legacyDestinationBytesParameters = fmt.Sprintf(`
  3257. "DestinationBytesMetricsASN" : "%s",
  3258. `, testGeoIPASN)
  3259. }
  3260. osshPrefix := ""
  3261. if applyOsshPrefix {
  3262. osshPrefix = fmt.Sprintf(`
  3263. "ServerOSSHPrefixSpecs": {
  3264. "TEST": [["", "\\x01{200}"]]
  3265. },
  3266. "OSSHPrefixSplitMinDelay": "30ms",
  3267. "OSSHPrefixSplitMaxDelay": "40ms",
  3268. "OSSHPrefixEnableFragmentor": %s,
  3269. `, strconv.FormatBool(enableOsshPrefixFragmenting))
  3270. }
  3271. restrictInproxyParameters := ""
  3272. if doRestrictAllInproxyProviderRegions {
  3273. restrictInproxyParameters = `
  3274. "RestrictInproxyProviderRegions": {"" : [""]},
  3275. "RestrictInproxyProviderIDsServerProbability": 1.0,
  3276. `
  3277. }
  3278. tacticsConfigJSON := fmt.Sprintf(
  3279. tacticsConfigJSONFormat,
  3280. tacticsRequestPublicKey,
  3281. tacticsRequestPrivateKey,
  3282. tacticsRequestObfuscatedKey,
  3283. burstParameters,
  3284. destinationBytesParameters,
  3285. legacyDestinationBytesParameters,
  3286. osshPrefix,
  3287. inproxyParametersJSON,
  3288. restrictInproxyParameters,
  3289. tunnelProtocol,
  3290. tunnelProtocol,
  3291. tunnelProtocol,
  3292. livenessTestSize,
  3293. livenessTestSize,
  3294. livenessTestSize,
  3295. livenessTestSize,
  3296. discoveryStategy,
  3297. propagationChannelID,
  3298. strings.ReplaceAll(testCustomHostNameRegex, `\`, `\\`),
  3299. tunnelProtocol)
  3300. err := ioutil.WriteFile(tacticsConfigFilename, []byte(tacticsConfigJSON), 0600)
  3301. if err != nil {
  3302. t.Fatalf("error paving tactics config file: %s", err)
  3303. }
  3304. }
  3305. func paveBlocklistFile(t *testing.T, blocklistFilename string) {
  3306. blocklistContent :=
  3307. "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"
  3308. err := ioutil.WriteFile(blocklistFilename, []byte(blocklistContent), 0600)
  3309. if err != nil {
  3310. t.Fatalf("error paving blocklist file: %s", err)
  3311. }
  3312. }
  3313. type inproxyTestConfig struct {
  3314. tacticsParametersJSON string
  3315. addMeekServerForBroker bool
  3316. brokerIPAddress string
  3317. brokerPort int
  3318. brokerSessionPublicKey string
  3319. brokerSessionPublicKeyCurve25519 string
  3320. brokerSessionPrivateKey string
  3321. brokerObfuscationRootSecret string
  3322. brokerServerEntrySignaturePublicKey string
  3323. brokerFrontingProviderID string
  3324. brokerServerCertificate string
  3325. brokerServerPrivateKey string
  3326. brokerMeekRequiredHeaders map[string]string
  3327. proxySessionPublicKey string
  3328. proxySessionPublicKeyCurve25519 string
  3329. proxySessionPrivateKey string
  3330. personalCompartmentID string
  3331. }
  3332. func generateInproxyTestConfig(
  3333. addMeekServerForBroker bool,
  3334. doTargetBrokerSpecs bool,
  3335. brokerIPAddress string,
  3336. brokerPort int,
  3337. serverEntrySignaturePublicKey string,
  3338. useInproxyMediaStreams bool) (*inproxyTestConfig, error) {
  3339. // Generate in-proxy configuration.
  3340. //
  3341. // In this test, a single common compartment ID is issued to all clients;
  3342. // the test client will get it via tactics.
  3343. //
  3344. // Because of singletons in the Psiphon client, there can only be a single
  3345. // Psiphon client instance in this test process, and so it must act as
  3346. // it's own in-proxy proxy.
  3347. //
  3348. // To minimize external dependencies, STUN testing is disabled here; it is
  3349. // exercised in the common/inproxy package tests.
  3350. //
  3351. // InproxyBrokerAllowCommonASNMatching and
  3352. // InproxyBrokerAllowBogonWebRTCConnections must be set to true in the
  3353. // server/broker config, to allow matches with the same local network
  3354. // address. InproxyDisableIPv6ICECandidates is turned on, in tactics,
  3355. // since the test GeoIP database is IPv4-only (see paveGeoIPDatabaseFiles).
  3356. commonCompartmentID, err := inproxy.MakeID()
  3357. if err != nil {
  3358. return nil, errors.Trace(err)
  3359. }
  3360. commonCompartmentIDStr := commonCompartmentID.String()
  3361. personalCompartmentID, err := inproxy.MakeID()
  3362. if err != nil {
  3363. return nil, errors.Trace(err)
  3364. }
  3365. personalCompartmentIDStr := personalCompartmentID.String()
  3366. brokerSessionPrivateKey, err := inproxy.GenerateSessionPrivateKey()
  3367. if err != nil {
  3368. return nil, errors.Trace(err)
  3369. }
  3370. brokerSessionPrivateKeyStr := brokerSessionPrivateKey.String()
  3371. brokerSessionPublicKey, err := brokerSessionPrivateKey.GetPublicKey()
  3372. if err != nil {
  3373. return nil, errors.Trace(err)
  3374. }
  3375. brokerSessionPublicKeyStr := brokerSessionPublicKey.String()
  3376. brokerSessionPublicKeyCurve25519, err := brokerSessionPublicKey.ToCurve25519()
  3377. if err != nil {
  3378. return nil, errors.Trace(err)
  3379. }
  3380. brokerSessionPublicKeyCurve25519Str := brokerSessionPublicKeyCurve25519.String()
  3381. brokerRootObfuscationSecret, err := inproxy.GenerateRootObfuscationSecret()
  3382. if err != nil {
  3383. return nil, errors.Trace(err)
  3384. }
  3385. brokerRootObfuscationSecretStr := brokerRootObfuscationSecret.String()
  3386. brokerFrontingProviderID := strings.ToUpper(prng.HexString(8))
  3387. brokerFrontingHostName := values.GetHostName()
  3388. brokerServerCertificate, brokerServerPrivateKey, brokerVerifyPin, err :=
  3389. common.GenerateWebServerCertificate(brokerFrontingHostName)
  3390. if err != nil {
  3391. return nil, errors.Trace(err)
  3392. }
  3393. brokerMeekRequiredHeaders := map[string]string{"X-MeekRequiredHeader": prng.HexString(32)}
  3394. proxySessionPrivateKey, err := inproxy.GenerateSessionPrivateKey()
  3395. if err != nil {
  3396. return nil, errors.Trace(err)
  3397. }
  3398. proxySessionPrivateKeyStr := proxySessionPrivateKey.String()
  3399. proxySessionPublicKey, err := proxySessionPrivateKey.GetPublicKey()
  3400. if err != nil {
  3401. return nil, errors.Trace(err)
  3402. }
  3403. proxySessionPublicKeyStr := proxySessionPublicKey.String()
  3404. proxySessionPublicKeyCurve25519, err := proxySessionPublicKey.ToCurve25519()
  3405. if err != nil {
  3406. return nil, errors.Trace(err)
  3407. }
  3408. proxySessionPublicKeyCurve25519Str := proxySessionPublicKeyCurve25519.String()
  3409. address := net.JoinHostPort(brokerIPAddress, strconv.Itoa(brokerPort))
  3410. addressRegex := strings.ReplaceAll(address, ".", "\\\\.")
  3411. skipVerify := false
  3412. verifyServerName := brokerFrontingHostName
  3413. verifyPins := fmt.Sprintf("[\"%s\"]", brokerVerifyPin)
  3414. if prng.FlipCoin() {
  3415. skipVerify = true
  3416. verifyServerName = ""
  3417. verifyPins = "[]"
  3418. }
  3419. brokerSpecJSONFormat := `
  3420. {
  3421. "BrokerPublicKey": "%s",
  3422. "BrokerRootObfuscationSecret": "%s",
  3423. "BrokerFrontingSpecs": [{
  3424. "FrontingProviderID": "%s",
  3425. "Addresses": ["%s"],
  3426. "DisableSNI": true,
  3427. "SkipVerify": %v,
  3428. "VerifyServerName": "%s",
  3429. "VerifyPins": %s,
  3430. "Host": "%s"
  3431. }]
  3432. }
  3433. `
  3434. validBrokerSpecJSON := fmt.Sprintf(
  3435. brokerSpecJSONFormat,
  3436. brokerSessionPublicKeyStr,
  3437. brokerRootObfuscationSecretStr,
  3438. brokerFrontingProviderID,
  3439. addressRegex,
  3440. skipVerify,
  3441. verifyServerName,
  3442. verifyPins,
  3443. brokerFrontingHostName)
  3444. otherSessionPrivateKey, _ := inproxy.GenerateSessionPrivateKey()
  3445. otherSessionPublicKey, _ := otherSessionPrivateKey.GetPublicKey()
  3446. otherRootObfuscationSecret, _ := inproxy.GenerateRootObfuscationSecret()
  3447. invalidBrokerSpecJSON := fmt.Sprintf(
  3448. brokerSpecJSONFormat,
  3449. otherSessionPublicKey.String(),
  3450. otherRootObfuscationSecret.String(),
  3451. prng.HexString(16),
  3452. prng.HexString(16),
  3453. false,
  3454. prng.HexString(16),
  3455. fmt.Sprintf("[\"%s\"]", prng.HexString(16)),
  3456. prng.HexString(16))
  3457. validBrokerSpecsJSON := fmt.Sprintf("[%s]", validBrokerSpecJSON)
  3458. invalidBrokerSpecsJSON := fmt.Sprintf("[%s]", invalidBrokerSpecJSON)
  3459. allBrokerSpecsJSON := fmt.Sprintf("[%s, %s]", validBrokerSpecJSON, invalidBrokerSpecJSON)
  3460. var brokerSpecsJSON, proxyBrokerSpecsJSON, clientBrokerSpecsJSON string
  3461. if doTargetBrokerSpecs {
  3462. // invalidBrokerSpecsJSON should be ignored when specific proxy/client
  3463. // broker specs are set.
  3464. brokerSpecsJSON = invalidBrokerSpecsJSON
  3465. proxyBrokerSpecsJSON = validBrokerSpecsJSON
  3466. clientBrokerSpecsJSON = validBrokerSpecsJSON
  3467. } else {
  3468. brokerSpecsJSON = validBrokerSpecsJSON
  3469. proxyBrokerSpecsJSON = "[]"
  3470. clientBrokerSpecsJSON = "[]"
  3471. }
  3472. additionalHeaders := http.Header{}
  3473. for name, value := range brokerMeekRequiredHeaders {
  3474. additionalHeaders[name] = []string{value}
  3475. }
  3476. additionalHeadersJSONBytes, _ := json.Marshal(additionalHeaders)
  3477. additionalHeadersJSON := string(additionalHeadersJSONBytes)
  3478. maxRequestTimeoutsJSON := ""
  3479. if prng.FlipCoin() {
  3480. maxRequestTimeoutsJSONFormat := `
  3481. "InproxyFrontingProviderClientMaxRequestTimeouts": {"%s": "10s"},
  3482. "InproxyFrontingProviderServerMaxRequestTimeouts": {"%s": "5s"},
  3483. `
  3484. maxRequestTimeoutsJSON = fmt.Sprintf(
  3485. maxRequestTimeoutsJSONFormat,
  3486. brokerFrontingProviderID,
  3487. brokerFrontingProviderID)
  3488. }
  3489. tacticsParametersJSONFormat := `
  3490. "InproxyAllowProxy": true,
  3491. "InproxyAllowClient": true,
  3492. "InproxyTunnelProtocolSelectionProbability": 1.0,
  3493. "InproxyAllBrokerSpecs": %s,
  3494. "InproxyBrokerSpecs": %s,
  3495. "InproxyProxyBrokerSpecs": %s,
  3496. "InproxyClientBrokerSpecs": %s,
  3497. "InproxyAllCommonCompartmentIDs": ["%s"],
  3498. "InproxyCommonCompartmentIDs": ["%s"],
  3499. "InproxyClientDiscoverNATProbability": 0.0,
  3500. "InproxyDisableSTUN": true,
  3501. "InproxyDisablePortMapping": true,
  3502. "InproxyDisableIPv6ICECandidates": true,
  3503. "InproxyWebRTCMediaStreamsProbability": %s,
  3504. "InproxyEnableProxyQuality": true,
  3505. "InproxyProxyQualityTargetUpstreamBytes": 1,
  3506. "InproxyProxyQualityTargetDownstreamBytes": 1,
  3507. "InproxyProxyQualityTargetDuration": "1ns",
  3508. "InproxyProxyQualityReporterTrustedCACertificates": "%s",
  3509. "InproxyProxyQualityReporterAdditionalHeaders": %s,
  3510. "InproxyProxyQualityReporterRequestDelay": 0,
  3511. %s
  3512. `
  3513. mediaStreamsProbability := "0.0"
  3514. if useInproxyMediaStreams {
  3515. mediaStreamsProbability = "1.0"
  3516. }
  3517. tacticsParametersJSON := fmt.Sprintf(
  3518. tacticsParametersJSONFormat,
  3519. allBrokerSpecsJSON,
  3520. brokerSpecsJSON,
  3521. proxyBrokerSpecsJSON,
  3522. clientBrokerSpecsJSON,
  3523. commonCompartmentIDStr,
  3524. commonCompartmentIDStr,
  3525. mediaStreamsProbability,
  3526. strings.ReplaceAll(brokerServerCertificate, "\n", "\\n"),
  3527. additionalHeadersJSON,
  3528. maxRequestTimeoutsJSON)
  3529. config := &inproxyTestConfig{
  3530. tacticsParametersJSON: tacticsParametersJSON,
  3531. addMeekServerForBroker: addMeekServerForBroker,
  3532. brokerIPAddress: brokerIPAddress,
  3533. brokerPort: brokerPort,
  3534. brokerSessionPrivateKey: brokerSessionPrivateKeyStr,
  3535. brokerSessionPublicKey: brokerSessionPublicKeyStr,
  3536. brokerSessionPublicKeyCurve25519: brokerSessionPublicKeyCurve25519Str,
  3537. brokerObfuscationRootSecret: brokerRootObfuscationSecretStr,
  3538. brokerServerEntrySignaturePublicKey: serverEntrySignaturePublicKey,
  3539. brokerFrontingProviderID: brokerFrontingProviderID,
  3540. brokerServerCertificate: brokerServerCertificate,
  3541. brokerServerPrivateKey: brokerServerPrivateKey,
  3542. brokerMeekRequiredHeaders: brokerMeekRequiredHeaders,
  3543. proxySessionPublicKey: proxySessionPublicKeyStr,
  3544. proxySessionPublicKeyCurve25519: proxySessionPublicKeyCurve25519Str,
  3545. proxySessionPrivateKey: proxySessionPrivateKeyStr,
  3546. personalCompartmentID: personalCompartmentIDStr,
  3547. }
  3548. return config, nil
  3549. }
  3550. type pruneServerEntryTestCase struct {
  3551. IPAddress string
  3552. ExplicitTag bool
  3553. ExpectedTag string
  3554. LocalTimestamp string
  3555. PsinetValid bool
  3556. ExpectPrune bool
  3557. IsEmbedded bool
  3558. DialPort0 bool
  3559. ServerEntryFields protocol.ServerEntryFields
  3560. }
  3561. func initializePruneServerEntriesTest(
  3562. t *testing.T,
  3563. runConfig *runServerConfig) ([]*pruneServerEntryTestCase, []string, int) {
  3564. if !runConfig.doPruneServerEntries {
  3565. return nil, nil, 0
  3566. }
  3567. newTimeStamp := time.Now().UTC().Format(time.RFC3339)
  3568. oldTimeStamp := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339)
  3569. // Test Cases:
  3570. // - ExplicitTag: server entry includes a tag; vs. generate a derived tag
  3571. // - LocalTimestamp: server entry is sufficiently old to be pruned; vs. not
  3572. // - PsinetValid: server entry is reported valid by psinet; vs. deleted
  3573. // - ExpectPrune: prune outcome based on flags above
  3574. // - IsEmbedded: pruned embedded server entries leave a tombstone and cannot
  3575. // be reimported
  3576. // - DialPort0: set dial port to 0, a special prune case (see statusAPIRequestHandler)
  3577. pruneServerEntryTestCases := []*pruneServerEntryTestCase{
  3578. {IPAddress: "192.0.2.1", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  3579. {IPAddress: "192.0.2.2", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: true, ExpectPrune: false},
  3580. {IPAddress: "192.0.2.3", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  3581. {IPAddress: "192.0.2.4", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: false},
  3582. {IPAddress: "192.0.2.5", ExplicitTag: true, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  3583. {IPAddress: "192.0.2.6", ExplicitTag: false, LocalTimestamp: newTimeStamp, PsinetValid: false, ExpectPrune: false},
  3584. {IPAddress: "192.0.2.7", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  3585. {IPAddress: "192.0.2.8", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: false},
  3586. {IPAddress: "192.0.2.9", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  3587. {IPAddress: "192.0.2.10", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: false, ExpectPrune: true, IsEmbedded: true},
  3588. {IPAddress: "192.0.2.11", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: false, DialPort0: true},
  3589. {IPAddress: "192.0.2.12", ExplicitTag: false, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  3590. {IPAddress: "192.0.2.13", ExplicitTag: true, LocalTimestamp: oldTimeStamp, PsinetValid: true, ExpectPrune: true, IsEmbedded: true, DialPort0: true},
  3591. }
  3592. for _, testCase := range pruneServerEntryTestCases {
  3593. dialPort := 4000
  3594. if testCase.DialPort0 {
  3595. dialPort = 0
  3596. }
  3597. _, _, _, _, encodedServerEntry, err := GenerateConfig(
  3598. &GenerateConfigParams{
  3599. ServerIPAddress: testCase.IPAddress,
  3600. TunnelProtocolPorts: map[string]int{runConfig.tunnelProtocol: dialPort},
  3601. })
  3602. if err != nil {
  3603. t.Fatalf("GenerateConfig failed: %s", err)
  3604. }
  3605. serverEntrySource := protocol.SERVER_ENTRY_SOURCE_REMOTE
  3606. if testCase.IsEmbedded {
  3607. serverEntrySource = protocol.SERVER_ENTRY_SOURCE_EMBEDDED
  3608. }
  3609. serverEntryFields, err := protocol.DecodeServerEntryFields(
  3610. string(encodedServerEntry),
  3611. testCase.LocalTimestamp,
  3612. serverEntrySource)
  3613. if err != nil {
  3614. t.Fatalf("DecodeServerEntryFields failed: %s", err)
  3615. }
  3616. // GenerateConfig now generates an explict tag for each server entry.
  3617. // To test the legacy case with no tag, delete it here.
  3618. delete(serverEntryFields, "tag")
  3619. if testCase.ExplicitTag {
  3620. testCase.ExpectedTag = prng.Base64String(32)
  3621. serverEntryFields.SetTag(testCase.ExpectedTag)
  3622. } else {
  3623. testCase.ExpectedTag = protocol.GenerateServerEntryTag(
  3624. serverEntryFields.GetIPAddress(),
  3625. serverEntryFields.GetWebServerSecret())
  3626. }
  3627. testCase.ServerEntryFields = serverEntryFields
  3628. }
  3629. psinetValidServerEntryTags := make([]string, 0)
  3630. expectedNumPruneNotices := 0
  3631. for _, testCase := range pruneServerEntryTestCases {
  3632. if testCase.PsinetValid {
  3633. psinetValidServerEntryTags = append(
  3634. psinetValidServerEntryTags, testCase.ExpectedTag)
  3635. }
  3636. if testCase.ExpectPrune {
  3637. expectedNumPruneNotices += 1
  3638. }
  3639. }
  3640. return pruneServerEntryTestCases,
  3641. psinetValidServerEntryTags,
  3642. expectedNumPruneNotices
  3643. }
  3644. func storePruneServerEntriesTest(
  3645. t *testing.T,
  3646. runConfig *runServerConfig,
  3647. testDataDirName string,
  3648. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  3649. if !runConfig.doPruneServerEntries {
  3650. return
  3651. }
  3652. for _, testCase := range pruneServerEntryTestCases {
  3653. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  3654. if err != nil {
  3655. t.Fatalf("StoreServerEntry failed: %s", err)
  3656. }
  3657. }
  3658. clientConfig := &psiphon.Config{
  3659. SponsorId: "0",
  3660. PropagationChannelId: "0",
  3661. // DataRootDirectory must to be set to avoid a migration in the current
  3662. // working directory.
  3663. DataRootDirectory: testDataDirName,
  3664. }
  3665. err := clientConfig.Commit(false)
  3666. if err != nil {
  3667. t.Fatalf("Commit failed: %s", err)
  3668. }
  3669. resolver := psiphon.NewResolver(clientConfig, true)
  3670. defer resolver.Stop()
  3671. clientConfig.SetResolver(resolver)
  3672. applyParameters := make(map[string]interface{})
  3673. applyParameters[parameters.RecordFailedTunnelPersistentStatsProbability] = 1.0
  3674. err = clientConfig.SetParameters("", true, applyParameters)
  3675. if err != nil {
  3676. t.Fatalf("SetParameters failed: %s", err)
  3677. }
  3678. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  3679. for _, testCase := range pruneServerEntryTestCases {
  3680. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  3681. }
  3682. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  3683. t *testing.T,
  3684. testCase *pruneServerEntryTestCase,
  3685. serverEntry *protocol.ServerEntry) {
  3686. verifyTestCasesStored.isStored(testCase.IPAddress)
  3687. // Check that random tag was retained or derived tag was calculated as
  3688. // expected
  3689. if serverEntry.Tag != testCase.ExpectedTag {
  3690. t.Fatalf("unexpected tag for %s got %s expected %s",
  3691. testCase.IPAddress, serverEntry.Tag, testCase.ExpectedTag)
  3692. }
  3693. // Create failed tunnel event records to exercise pruning
  3694. dialParams, err := psiphon.MakeDialParameters(
  3695. clientConfig,
  3696. nil,
  3697. nil,
  3698. nil,
  3699. nil,
  3700. func(_ *protocol.ServerEntry, _ string) bool { return true },
  3701. func(serverEntry *protocol.ServerEntry) (string, bool) {
  3702. return runConfig.tunnelProtocol, true
  3703. },
  3704. serverEntry,
  3705. nil,
  3706. nil,
  3707. false,
  3708. 0,
  3709. 0)
  3710. if err != nil {
  3711. t.Fatalf("MakeDialParameters failed: %s", err)
  3712. }
  3713. err = psiphon.RecordFailedTunnelStat(
  3714. clientConfig, dialParams, nil, 0, 0, std_errors.New("test error"))
  3715. if err != nil {
  3716. t.Fatalf("RecordFailedTunnelStat failed: %s", err)
  3717. }
  3718. })
  3719. verifyTestCasesStored.checkStored(
  3720. t, "missing prune test case server entries")
  3721. }
  3722. func checkPruneServerEntriesTest(
  3723. t *testing.T,
  3724. runConfig *runServerConfig,
  3725. testDataDirName string,
  3726. pruneServerEntryTestCases []*pruneServerEntryTestCase) {
  3727. if !runConfig.doPruneServerEntries {
  3728. return
  3729. }
  3730. clientConfig := &psiphon.Config{
  3731. SponsorId: "0",
  3732. PropagationChannelId: "0",
  3733. // DataRootDirectory must to be set to avoid a migration in the current
  3734. // working directory.
  3735. DataRootDirectory: testDataDirName,
  3736. }
  3737. err := clientConfig.Commit(false)
  3738. if err != nil {
  3739. t.Fatalf("Commit failed: %s", err)
  3740. }
  3741. // Check that server entries remain or are pruned as expected
  3742. verifyTestCasesStored := make(verifyTestCasesStoredLookup)
  3743. for _, testCase := range pruneServerEntryTestCases {
  3744. if !testCase.ExpectPrune {
  3745. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  3746. }
  3747. }
  3748. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  3749. t *testing.T,
  3750. testCase *pruneServerEntryTestCase,
  3751. serverEntry *protocol.ServerEntry) {
  3752. if testCase.ExpectPrune {
  3753. t.Fatalf("expected prune for %s", testCase.IPAddress)
  3754. } else {
  3755. verifyTestCasesStored.isStored(testCase.IPAddress)
  3756. }
  3757. })
  3758. verifyTestCasesStored.checkStored(
  3759. t, "missing prune test case server entries")
  3760. // Check that pruned server entries reimport or not, as expected
  3761. for _, testCase := range pruneServerEntryTestCases {
  3762. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  3763. if err != nil {
  3764. t.Fatalf("StoreServerEntry failed: %s", err)
  3765. }
  3766. }
  3767. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  3768. for _, testCase := range pruneServerEntryTestCases {
  3769. if !testCase.ExpectPrune || !testCase.IsEmbedded {
  3770. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  3771. }
  3772. }
  3773. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  3774. t *testing.T,
  3775. testCase *pruneServerEntryTestCase,
  3776. serverEntry *protocol.ServerEntry) {
  3777. if testCase.ExpectPrune && testCase.IsEmbedded {
  3778. t.Fatalf("expected tombstone for %s", testCase.IPAddress)
  3779. } else {
  3780. verifyTestCasesStored.isStored(testCase.IPAddress)
  3781. }
  3782. })
  3783. verifyTestCasesStored.checkStored(
  3784. t, "missing reimported prune test case server entries")
  3785. // Non-embedded server entries with tombstones _can_ be reimported
  3786. for _, testCase := range pruneServerEntryTestCases {
  3787. testCase.ServerEntryFields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_REMOTE)
  3788. err := psiphon.StoreServerEntry(testCase.ServerEntryFields, true)
  3789. if err != nil {
  3790. t.Fatalf("StoreServerEntry failed: %s", err)
  3791. }
  3792. }
  3793. verifyTestCasesStored = make(verifyTestCasesStoredLookup)
  3794. for _, testCase := range pruneServerEntryTestCases {
  3795. verifyTestCasesStored.mustBeStored(testCase.IPAddress)
  3796. }
  3797. scanServerEntries(t, clientConfig, pruneServerEntryTestCases, func(
  3798. t *testing.T,
  3799. testCase *pruneServerEntryTestCase,
  3800. serverEntry *protocol.ServerEntry) {
  3801. verifyTestCasesStored.isStored(testCase.IPAddress)
  3802. })
  3803. verifyTestCasesStored.checkStored(
  3804. t, "missing non-embedded reimported prune test case server entries")
  3805. }
  3806. func scanServerEntries(
  3807. t *testing.T,
  3808. clientConfig *psiphon.Config,
  3809. pruneServerEntryTestCases []*pruneServerEntryTestCase,
  3810. scanner func(
  3811. t *testing.T,
  3812. testCase *pruneServerEntryTestCase,
  3813. serverEntry *protocol.ServerEntry)) {
  3814. _, iterator, err := psiphon.NewServerEntryIterator(clientConfig)
  3815. if err != nil {
  3816. t.Fatalf("NewServerEntryIterator failed: %s", err)
  3817. }
  3818. defer iterator.Close()
  3819. for {
  3820. serverEntry, err := iterator.Next()
  3821. if err != nil {
  3822. t.Fatalf("ServerIterator.Next failed: %s", err)
  3823. }
  3824. if serverEntry == nil {
  3825. break
  3826. }
  3827. for _, testCase := range pruneServerEntryTestCases {
  3828. if testCase.IPAddress == serverEntry.IpAddress {
  3829. scanner(t, testCase, serverEntry)
  3830. break
  3831. }
  3832. }
  3833. }
  3834. }
  3835. type verifyTestCasesStoredLookup map[string]bool
  3836. func (v verifyTestCasesStoredLookup) mustBeStored(s string) {
  3837. v[s] = true
  3838. }
  3839. func (v verifyTestCasesStoredLookup) isStored(s string) {
  3840. delete(v, s)
  3841. }
  3842. func (v verifyTestCasesStoredLookup) checkStored(t *testing.T, errMessage string) {
  3843. if len(v) != 0 {
  3844. t.Fatalf("%s: %+v", errMessage, v)
  3845. }
  3846. }
  3847. type Number interface {
  3848. int64 | float64
  3849. }
  3850. // testSampleInUniformRange returns true if sample is in the range [a, b],
  3851. // or within 2 standard deviations of the range.
  3852. func testSampleInUniformRange[V Number](sample, a, b, stddev V) bool {
  3853. if sample >= a && sample <= b {
  3854. return true
  3855. }
  3856. lower := math.Abs(float64(sample-a) / float64(stddev))
  3857. higher := math.Abs(float64(sample-b) / float64(stddev))
  3858. return lower <= 2.0 || higher <= 2.0
  3859. }
  3860. type flowInspectorProxy struct {
  3861. listener *socks.SocksListener
  3862. ch chan []*flows
  3863. }
  3864. func newFlowInspectorProxy() (*flowInspectorProxy, error) {
  3865. listener, err := socks.ListenSocks("tcp", "127.0.0.1:0")
  3866. if err != nil {
  3867. fmt.Printf("socks.ListenSocks failed: %s\n", err)
  3868. return nil, err
  3869. }
  3870. return &flowInspectorProxy{
  3871. listener: listener,
  3872. ch: make(chan []*flows, 1),
  3873. }, nil
  3874. }
  3875. func (f *flowInspectorProxy) start() {
  3876. go func() {
  3877. for {
  3878. localConn, err := f.listener.AcceptSocks()
  3879. if err != nil {
  3880. return
  3881. }
  3882. go func() {
  3883. defer localConn.Close()
  3884. remoteConn, err := net.Dial("tcp", localConn.Req.Target)
  3885. if err != nil {
  3886. fmt.Printf("net.Dial failed: %s\n", err)
  3887. return
  3888. }
  3889. defer remoteConn.Close()
  3890. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  3891. if err != nil {
  3892. fmt.Printf("localConn.Grant failed: %s\n", err)
  3893. return
  3894. }
  3895. waitGroup := new(sync.WaitGroup)
  3896. waitGroup.Add(1)
  3897. serverFlowWriter := newFlowWriter(true)
  3898. clientFlowWriter := newFlowWriter(false)
  3899. go func() {
  3900. defer waitGroup.Done()
  3901. // Copy from remote to local, and tee to serverFlowWriter.
  3902. io.Copy(localConn, io.TeeReader(remoteConn, serverFlowWriter))
  3903. // fmt.Printf("Server Flows:\n%s\n\n", serverFlowWriter.String())
  3904. localConn.Close()
  3905. remoteConn.Close()
  3906. }()
  3907. // Copy from local to remote, and tee to clientFlowWriter.
  3908. io.Copy(remoteConn, io.TeeReader(localConn, clientFlowWriter))
  3909. // fmt.Printf("Client Flows:\n%s\n\n", clientFlowWriter.String())
  3910. localConn.Close()
  3911. remoteConn.Close()
  3912. waitGroup.Wait()
  3913. // clientFlowWriter and serverFlowWriter are synchronized by waitGroup.
  3914. f.ch <- []*flows{serverFlowWriter, clientFlowWriter}
  3915. }()
  3916. }
  3917. }()
  3918. }
  3919. func (f *flowInspectorProxy) close() error {
  3920. return f.listener.Close()
  3921. }
  3922. type flow struct {
  3923. // timeDelta is the time elapsed since the last flow
  3924. timeDelta time.Duration
  3925. data []byte
  3926. }
  3927. type flows struct {
  3928. lastTime time.Time
  3929. server bool
  3930. streamDump *bytes.Buffer
  3931. flows []flow
  3932. }
  3933. func newFlowWriter(server bool) *flows {
  3934. return &flows{
  3935. lastTime: time.Now(),
  3936. streamDump: new(bytes.Buffer),
  3937. server: server,
  3938. }
  3939. }
  3940. // String returns a string representation of the first 10 flows.
  3941. func (f *flows) String() string {
  3942. var sb strings.Builder
  3943. for i, flow := range f.flows[:10] {
  3944. sb.WriteString(fmt.Sprintf("Flow %d: %.5f ms: %s\n",
  3945. i, flow.timeDelta.Seconds()*1000, hex.EncodeToString(flow.data)))
  3946. }
  3947. if len(f.flows) > 10 {
  3948. sb.WriteString("...\n")
  3949. }
  3950. return sb.String()
  3951. }
  3952. func (f *flows) Write(p []byte) (n int, err error) {
  3953. curTime := time.Now()
  3954. _, err = f.streamDump.Write(p)
  3955. if err != nil {
  3956. return 0, err
  3957. }
  3958. data := make([]byte, len(p))
  3959. n = copy(data, p)
  3960. if n < len(p) {
  3961. return n, io.ErrShortWrite
  3962. }
  3963. f.flows = append(f.flows, flow{
  3964. timeDelta: time.Since(f.lastTime),
  3965. data: data,
  3966. })
  3967. f.lastTime = curTime
  3968. return n, err
  3969. }
  3970. // newDiscoveryServers returns len(ipAddresses) discovery servers with the
  3971. // given IP addresses and randomly generated tags.
  3972. func newDiscoveryServers(ipAddresses []string) ([]*psinet.DiscoveryServer, error) {
  3973. servers := make([]*psinet.DiscoveryServer, len(ipAddresses))
  3974. for i, ipAddress := range ipAddresses {
  3975. encodedServer, err := protocol.EncodeServerEntry(&protocol.ServerEntry{
  3976. IpAddress: ipAddress,
  3977. Tag: prng.HexString(16),
  3978. })
  3979. if err != nil {
  3980. return nil, errors.Trace(err)
  3981. }
  3982. servers[i] = &psinet.DiscoveryServer{
  3983. DiscoveryDateRange: []time.Time{
  3984. time.Now().Add(-time.Hour).UTC(),
  3985. time.Now().Add(time.Hour).UTC(),
  3986. },
  3987. EncodedServerEntry: encodedServer,
  3988. }
  3989. }
  3990. return servers, nil
  3991. }