server_test.go 163 KB

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