server_test.go 159 KB

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