server_test.go 121 KB

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