server_test.go 111 KB

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