server_test.go 125 KB

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