server_test.go 134 KB

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