server_test.go 130 KB

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