server_test.go 141 KB

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