server_test.go 156 KB

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