server_test.go 129 KB

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