tunnelServer.go 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829
  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. "crypto/rand"
  24. "crypto/subtle"
  25. "encoding/base64"
  26. "encoding/json"
  27. std_errors "errors"
  28. "fmt"
  29. "io"
  30. "io/ioutil"
  31. "net"
  32. "strconv"
  33. "sync"
  34. "sync/atomic"
  35. "syscall"
  36. "time"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/monotime"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  46. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  47. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  48. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  49. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/refraction"
  50. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  51. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  52. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  53. "github.com/marusama/semaphore"
  54. cache "github.com/patrickmn/go-cache"
  55. )
  56. const (
  57. SSH_AUTH_LOG_PERIOD = 30 * time.Minute
  58. SSH_HANDSHAKE_TIMEOUT = 30 * time.Second
  59. SSH_BEGIN_HANDSHAKE_TIMEOUT = 1 * time.Second
  60. SSH_CONNECTION_READ_DEADLINE = 5 * time.Minute
  61. SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE = 8192
  62. SSH_TCP_PORT_FORWARD_QUEUE_SIZE = 1024
  63. SSH_KEEP_ALIVE_PAYLOAD_MIN_BYTES = 0
  64. SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES = 256
  65. SSH_SEND_OSL_INITIAL_RETRY_DELAY = 30 * time.Second
  66. SSH_SEND_OSL_RETRY_FACTOR = 2
  67. GEOIP_SESSION_CACHE_TTL = 60 * time.Minute
  68. OSL_SESSION_CACHE_TTL = 5 * time.Minute
  69. MAX_AUTHORIZATIONS = 16
  70. PRE_HANDSHAKE_RANDOM_STREAM_MAX_COUNT = 1
  71. RANDOM_STREAM_MAX_BYTES = 10485760
  72. ALERT_REQUEST_QUEUE_BUFFER_SIZE = 16
  73. )
  74. // TunnelServer is the main server that accepts Psiphon client
  75. // connections, via various obfuscation protocols, and provides
  76. // port forwarding (TCP and UDP) services to the Psiphon client.
  77. // At its core, TunnelServer is an SSH server. SSH is the base
  78. // protocol that provides port forward multiplexing, and transport
  79. // security. Layered on top of SSH, optionally, is Obfuscated SSH
  80. // and meek protocols, which provide further circumvention
  81. // capabilities.
  82. type TunnelServer struct {
  83. runWaitGroup *sync.WaitGroup
  84. listenerError chan error
  85. shutdownBroadcast <-chan struct{}
  86. sshServer *sshServer
  87. }
  88. type sshListener struct {
  89. net.Listener
  90. localAddress string
  91. tunnelProtocol string
  92. port int
  93. BPFProgramName string
  94. }
  95. // NewTunnelServer initializes a new tunnel server.
  96. func NewTunnelServer(
  97. support *SupportServices,
  98. shutdownBroadcast <-chan struct{}) (*TunnelServer, error) {
  99. sshServer, err := newSSHServer(support, shutdownBroadcast)
  100. if err != nil {
  101. return nil, errors.Trace(err)
  102. }
  103. return &TunnelServer{
  104. runWaitGroup: new(sync.WaitGroup),
  105. listenerError: make(chan error),
  106. shutdownBroadcast: shutdownBroadcast,
  107. sshServer: sshServer,
  108. }, nil
  109. }
  110. // Run runs the tunnel server; this function blocks while running a selection of
  111. // listeners that handle connections using various obfuscation protocols.
  112. //
  113. // Run listens on each designated tunnel port and spawns new goroutines to handle
  114. // each client connection. It halts when shutdownBroadcast is signaled. A list of active
  115. // clients is maintained, and when halting all clients are cleanly shutdown.
  116. //
  117. // Each client goroutine handles its own obfuscation (optional), SSH handshake, SSH
  118. // authentication, and then looping on client new channel requests. "direct-tcpip"
  119. // channels, dynamic port fowards, are supported. When the UDPInterceptUdpgwServerAddress
  120. // config parameter is configured, UDP port forwards over a TCP stream, following
  121. // the udpgw protocol, are handled.
  122. //
  123. // A new goroutine is spawned to handle each port forward for each client. Each port
  124. // forward tracks its bytes transferred. Overall per-client stats for connection duration,
  125. // GeoIP, number of port forwards, and bytes transferred are tracked and logged when the
  126. // client shuts down.
  127. //
  128. // Note: client handler goroutines may still be shutting down after Run() returns. See
  129. // comment in sshClient.stop(). TODO: fully synchronized shutdown.
  130. func (server *TunnelServer) Run() error {
  131. // TODO: should TunnelServer hold its own support pointer?
  132. support := server.sshServer.support
  133. // First bind all listeners; once all are successful,
  134. // start accepting connections on each.
  135. var listeners []*sshListener
  136. for tunnelProtocol, listenPort := range support.Config.TunnelProtocolPorts {
  137. localAddress := net.JoinHostPort(
  138. support.Config.ServerIPAddress, strconv.Itoa(listenPort))
  139. var listener net.Listener
  140. var BPFProgramName string
  141. var err error
  142. if protocol.TunnelProtocolUsesFrontedMeekQUIC(tunnelProtocol) {
  143. // For FRONTED-MEEK-QUIC-OSSH, no listener implemented. The edge-to-server
  144. // hop uses HTTPS and the client tunnel protocol is distinguished using
  145. // protocol.MeekCookieData.ClientTunnelProtocol.
  146. continue
  147. } else if protocol.TunnelProtocolUsesQUIC(tunnelProtocol) {
  148. // in-proxy QUIC tunnel protocols don't support gQUIC.
  149. enableGQUIC := support.Config.EnableGQUIC && !protocol.TunnelProtocolUsesInproxy(tunnelProtocol)
  150. logTunnelProtocol := tunnelProtocol
  151. listener, err = quic.Listen(
  152. CommonLogger(log),
  153. func(peerAddress string, err error, logFields common.LogFields) {
  154. logIrregularTunnel(
  155. support, logTunnelProtocol, listenPort, peerAddress,
  156. errors.Trace(err), LogFields(logFields))
  157. },
  158. localAddress,
  159. support.Config.ObfuscatedSSHKey,
  160. enableGQUIC)
  161. } else if protocol.TunnelProtocolUsesRefractionNetworking(tunnelProtocol) {
  162. listener, err = refraction.Listen(localAddress)
  163. } else if protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  164. listener, err = net.Listen("tcp", localAddress)
  165. } else {
  166. // Only direct, unfronted protocol listeners use TCP BPF circumvention
  167. // programs.
  168. listener, BPFProgramName, err = newTCPListenerWithBPF(support, localAddress)
  169. if protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  170. listener, err = ListenTLSTunnel(support, listener, tunnelProtocol, listenPort)
  171. if err != nil {
  172. return errors.Trace(err)
  173. }
  174. }
  175. }
  176. if err != nil {
  177. for _, existingListener := range listeners {
  178. existingListener.Listener.Close()
  179. }
  180. return errors.Trace(err)
  181. }
  182. tacticsListener := NewTacticsListener(
  183. support,
  184. listener,
  185. tunnelProtocol,
  186. func(IP string) GeoIPData { return support.GeoIPService.Lookup(IP) })
  187. log.WithTraceFields(
  188. LogFields{
  189. "localAddress": localAddress,
  190. "tunnelProtocol": tunnelProtocol,
  191. "BPFProgramName": BPFProgramName,
  192. }).Info("listening")
  193. listeners = append(
  194. listeners,
  195. &sshListener{
  196. Listener: tacticsListener,
  197. localAddress: localAddress,
  198. port: listenPort,
  199. tunnelProtocol: tunnelProtocol,
  200. BPFProgramName: BPFProgramName,
  201. })
  202. }
  203. for _, listener := range listeners {
  204. server.runWaitGroup.Add(1)
  205. go func(listener *sshListener) {
  206. defer server.runWaitGroup.Done()
  207. log.WithTraceFields(
  208. LogFields{
  209. "localAddress": listener.localAddress,
  210. "tunnelProtocol": listener.tunnelProtocol,
  211. }).Info("running")
  212. server.sshServer.runListener(
  213. listener,
  214. server.listenerError)
  215. log.WithTraceFields(
  216. LogFields{
  217. "localAddress": listener.localAddress,
  218. "tunnelProtocol": listener.tunnelProtocol,
  219. }).Info("stopped")
  220. }(listener)
  221. }
  222. var err error
  223. select {
  224. case <-server.shutdownBroadcast:
  225. case err = <-server.listenerError:
  226. }
  227. for _, listener := range listeners {
  228. listener.Close()
  229. }
  230. server.sshServer.stopClients()
  231. server.runWaitGroup.Wait()
  232. log.WithTrace().Info("stopped")
  233. return err
  234. }
  235. // GetLoadStats returns load stats for the tunnel server. The stats are
  236. // broken down by protocol ("SSH", "OSSH", etc.) and type. Types of stats
  237. // include current connected client count, total number of current port
  238. // forwards.
  239. func (server *TunnelServer) GetLoadStats() (
  240. UpstreamStats, ProtocolStats, RegionStats) {
  241. return server.sshServer.getLoadStats()
  242. }
  243. // GetEstablishedClientCount returns the number of currently established
  244. // clients.
  245. func (server *TunnelServer) GetEstablishedClientCount() int {
  246. return server.sshServer.getEstablishedClientCount()
  247. }
  248. // ResetAllClientTrafficRules resets all established client traffic rules
  249. // to use the latest config and client properties. Any existing traffic
  250. // rule state is lost, including throttling state.
  251. func (server *TunnelServer) ResetAllClientTrafficRules() {
  252. server.sshServer.resetAllClientTrafficRules()
  253. }
  254. // ResetAllClientOSLConfigs resets all established client OSL state to use
  255. // the latest OSL config. Any existing OSL state is lost, including partial
  256. // progress towards SLOKs.
  257. func (server *TunnelServer) ResetAllClientOSLConfigs() {
  258. server.sshServer.resetAllClientOSLConfigs()
  259. }
  260. // ReloadTactics signals components that use server-side tactics for one-time
  261. // initialization to reload and use potentially changed parameters.
  262. func (server *TunnelServer) ReloadTactics() error {
  263. return errors.Trace(server.sshServer.reloadTactics())
  264. }
  265. // SetEstablishTunnels sets whether new tunnels may be established or not.
  266. // When not establishing, incoming connections are immediately closed.
  267. func (server *TunnelServer) SetEstablishTunnels(establish bool) {
  268. server.sshServer.setEstablishTunnels(establish)
  269. }
  270. // CheckEstablishTunnels returns whether new tunnels may be established or
  271. // not, and increments a metrics counter when establishment is disallowed.
  272. func (server *TunnelServer) CheckEstablishTunnels() bool {
  273. return server.sshServer.checkEstablishTunnels()
  274. }
  275. // GetEstablishTunnelsMetrics returns whether tunnel establishment is
  276. // currently allowed and the number of tunnels rejected since due to not
  277. // establishing since the last GetEstablishTunnelsMetrics call.
  278. func (server *TunnelServer) GetEstablishTunnelsMetrics() (bool, int64) {
  279. return server.sshServer.getEstablishTunnelsMetrics()
  280. }
  281. type sshServer struct {
  282. // Note: 64-bit ints used with atomic operations are placed
  283. // at the start of struct to ensure 64-bit alignment.
  284. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  285. lastAuthLog int64
  286. authFailedCount int64
  287. establishLimitedCount int64
  288. support *SupportServices
  289. establishTunnels int32
  290. concurrentSSHHandshakes semaphore.Semaphore
  291. shutdownBroadcast <-chan struct{}
  292. sshHostKey ssh.Signer
  293. obfuscatorSeedHistory *obfuscator.SeedHistory
  294. inproxyBrokerSessions *inproxy.ServerBrokerSessions
  295. clientsMutex sync.Mutex
  296. stoppingClients bool
  297. acceptedClientCounts map[string]map[string]int64
  298. clients map[string]*sshClient
  299. geoIPSessionCache *cache.Cache
  300. oslSessionCacheMutex sync.Mutex
  301. oslSessionCache *cache.Cache
  302. authorizationSessionIDsMutex sync.Mutex
  303. authorizationSessionIDs map[string]string
  304. meekServersMutex sync.Mutex
  305. meekServers []*MeekServer
  306. }
  307. func newSSHServer(
  308. support *SupportServices,
  309. shutdownBroadcast <-chan struct{}) (*sshServer, error) {
  310. privateKey, err := ssh.ParseRawPrivateKey([]byte(support.Config.SSHPrivateKey))
  311. if err != nil {
  312. return nil, errors.Trace(err)
  313. }
  314. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  315. signer, err := ssh.NewSignerFromKey(privateKey)
  316. if err != nil {
  317. return nil, errors.Trace(err)
  318. }
  319. var concurrentSSHHandshakes semaphore.Semaphore
  320. if support.Config.MaxConcurrentSSHHandshakes > 0 {
  321. concurrentSSHHandshakes = semaphore.New(support.Config.MaxConcurrentSSHHandshakes)
  322. }
  323. // The geoIPSessionCache replaces the legacy cache that used to be in
  324. // GeoIPServices and was used for the now-retired web API. That cache was
  325. // also used for, and now geoIPSessionCache provides:
  326. // - Determining first-tunnel-in-session (from a single server's point of
  327. // view)
  328. // - GeoIP for duplicate authorizations logic.
  329. //
  330. // TODO: combine geoIPSessionCache with oslSessionCache; need to deal with
  331. // OSL flush on hot reload and reconcile differing TTLs.
  332. geoIPSessionCache := cache.New(GEOIP_SESSION_CACHE_TTL, 1*time.Minute)
  333. // The OSL session cache temporarily retains OSL seed state
  334. // progress for disconnected clients. This enables clients
  335. // that disconnect and immediately reconnect to the same
  336. // server to resume their OSL progress. Cached progress
  337. // is referenced by session ID and is retained for
  338. // OSL_SESSION_CACHE_TTL after disconnect.
  339. //
  340. // Note: session IDs are assumed to be unpredictable. If a
  341. // rogue client could guess the session ID of another client,
  342. // it could resume its OSL progress and, if the OSL config
  343. // were known, infer some activity.
  344. oslSessionCache := cache.New(OSL_SESSION_CACHE_TTL, 1*time.Minute)
  345. // inproxyBrokerSessions are the secure in-proxy broker/server sessions
  346. // used to relay information from the broker to the server, including the
  347. // original in-proxy client IP and the in-proxy proxy ID.
  348. //
  349. // Only brokers with public keys configured in the
  350. // InproxyAllBrokerPublicKeys tactic parameter are allowed to connect to
  351. // the server, and brokers verify the server's public key via the
  352. // InproxySessionPublicKey server entry field.
  353. //
  354. // Sessions are initialized and run for all psiphond instances running any
  355. // in-proxy tunnel protocol.
  356. var inproxyBrokerSessions *inproxy.ServerBrokerSessions
  357. runningInproxy := false
  358. for tunnelProtocol, _ := range support.Config.TunnelProtocolPorts {
  359. if protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  360. runningInproxy = true
  361. break
  362. }
  363. }
  364. if runningInproxy {
  365. inproxyPrivateKey, err := inproxy.SessionPrivateKeyFromString(
  366. support.Config.InproxyServerSessionPrivateKey)
  367. if err != nil {
  368. return nil, errors.Trace(err)
  369. }
  370. inproxyObfuscationSecret, err := inproxy.ObfuscationSecretFromString(
  371. support.Config.InproxyServerObfuscationRootSecret)
  372. if err != nil {
  373. return nil, errors.Trace(err)
  374. }
  375. // The expected broker public keys are set in reloadTactics directly
  376. // below, so none are set here.
  377. inproxyBrokerSessions, err = inproxy.NewServerBrokerSessions(
  378. inproxyPrivateKey, inproxyObfuscationSecret, nil)
  379. if err != nil {
  380. return nil, errors.Trace(err)
  381. }
  382. }
  383. sshServer := &sshServer{
  384. support: support,
  385. establishTunnels: 1,
  386. concurrentSSHHandshakes: concurrentSSHHandshakes,
  387. shutdownBroadcast: shutdownBroadcast,
  388. sshHostKey: signer,
  389. acceptedClientCounts: make(map[string]map[string]int64),
  390. clients: make(map[string]*sshClient),
  391. geoIPSessionCache: geoIPSessionCache,
  392. oslSessionCache: oslSessionCache,
  393. authorizationSessionIDs: make(map[string]string),
  394. obfuscatorSeedHistory: obfuscator.NewSeedHistory(nil),
  395. inproxyBrokerSessions: inproxyBrokerSessions,
  396. }
  397. // Initialize components that use server-side tactics and which reload on
  398. // tactics change events.
  399. err = sshServer.reloadTactics()
  400. if err != nil {
  401. return nil, errors.Trace(err)
  402. }
  403. return sshServer, nil
  404. }
  405. func (sshServer *sshServer) setEstablishTunnels(establish bool) {
  406. // Do nothing when the setting is already correct. This avoids
  407. // spurious log messages when setEstablishTunnels is called
  408. // periodically with the same setting.
  409. if establish == (atomic.LoadInt32(&sshServer.establishTunnels) == 1) {
  410. return
  411. }
  412. establishFlag := int32(1)
  413. if !establish {
  414. establishFlag = 0
  415. }
  416. atomic.StoreInt32(&sshServer.establishTunnels, establishFlag)
  417. log.WithTraceFields(
  418. LogFields{"establish": establish}).Info("establishing tunnels")
  419. }
  420. func (sshServer *sshServer) checkEstablishTunnels() bool {
  421. establishTunnels := atomic.LoadInt32(&sshServer.establishTunnels) == 1
  422. if !establishTunnels {
  423. atomic.AddInt64(&sshServer.establishLimitedCount, 1)
  424. }
  425. return establishTunnels
  426. }
  427. func (sshServer *sshServer) getEstablishTunnelsMetrics() (bool, int64) {
  428. return atomic.LoadInt32(&sshServer.establishTunnels) == 1,
  429. atomic.SwapInt64(&sshServer.establishLimitedCount, 0)
  430. }
  431. // additionalTransportData is additional data gathered at transport level,
  432. // such as in MeekServer at the HTTP layer, and relayed to the
  433. // sshServer/sshClient.
  434. type additionalTransportData struct {
  435. overrideTunnelProtocol string
  436. steeringIP string
  437. }
  438. // runListener is intended to run an a goroutine; it blocks
  439. // running a particular listener. If an unrecoverable error
  440. // occurs, it will send the error to the listenerError channel.
  441. func (sshServer *sshServer) runListener(sshListener *sshListener, listenerError chan<- error) {
  442. handleClient := func(conn net.Conn, transportData *additionalTransportData) {
  443. // Note: establish tunnel limiter cannot simply stop TCP
  444. // listeners in all cases (e.g., meek) since SSH tunnels can
  445. // span multiple TCP connections.
  446. if !sshServer.checkEstablishTunnels() {
  447. log.WithTrace().Debug("not establishing tunnels")
  448. conn.Close()
  449. return
  450. }
  451. // sshListener.tunnelProtocol indictes the tunnel protocol run by the
  452. // listener. For direct protocols, this is also the client tunnel protocol.
  453. // For fronted protocols, the client may use a different protocol to connect
  454. // to the front and then only the front-to-Psiphon server will use the
  455. // listener protocol.
  456. //
  457. // A fronted meek client, for example, reports its first hop protocol in
  458. // protocol.MeekCookieData.ClientTunnelProtocol. Most metrics record this
  459. // value as relay_protocol, since the first hop is the one subject to
  460. // adversarial conditions. In some cases, such as irregular tunnels, there
  461. // is no ClientTunnelProtocol value available and the listener tunnel
  462. // protocol will be logged.
  463. //
  464. // Similarly, listenerPort indicates the listening port, which is the dialed
  465. // port number for direct protocols; while, for fronted protocols, the
  466. // client may dial a different port for its first hop.
  467. // Process each client connection concurrently.
  468. go sshServer.handleClient(sshListener, conn, transportData)
  469. }
  470. // Note: when exiting due to a unrecoverable error, be sure
  471. // to try to send the error to listenerError so that the outer
  472. // TunnelServer.Run will properly shut down instead of remaining
  473. // running.
  474. if protocol.TunnelProtocolUsesMeekHTTP(sshListener.tunnelProtocol) ||
  475. protocol.TunnelProtocolUsesMeekHTTPS(sshListener.tunnelProtocol) {
  476. if sshServer.tunnelProtocolUsesTLSDemux(sshListener.tunnelProtocol) {
  477. sshServer.runMeekTLSOSSHDemuxListener(sshListener, listenerError, handleClient)
  478. } else {
  479. meekServer, err := NewMeekServer(
  480. sshServer.support,
  481. sshListener.Listener,
  482. sshListener.tunnelProtocol,
  483. sshListener.port,
  484. protocol.TunnelProtocolUsesMeekHTTPS(sshListener.tunnelProtocol),
  485. protocol.TunnelProtocolUsesFrontedMeek(sshListener.tunnelProtocol),
  486. protocol.TunnelProtocolUsesObfuscatedSessionTickets(sshListener.tunnelProtocol),
  487. true,
  488. handleClient,
  489. sshServer.shutdownBroadcast)
  490. if err == nil {
  491. sshServer.registerMeekServer(meekServer)
  492. err = meekServer.Run()
  493. }
  494. if err != nil {
  495. select {
  496. case listenerError <- errors.Trace(err):
  497. default:
  498. }
  499. return
  500. }
  501. }
  502. } else {
  503. runListener(sshListener.Listener, sshServer.shutdownBroadcast, listenerError, "", handleClient)
  504. }
  505. }
  506. // runMeekTLSOSSHDemuxListener blocks running a listener which demuxes meek and
  507. // TLS-OSSH connections received on the same port.
  508. func (sshServer *sshServer) runMeekTLSOSSHDemuxListener(
  509. sshListener *sshListener,
  510. listenerError chan<- error,
  511. handleClient func(conn net.Conn, transportData *additionalTransportData)) {
  512. meekClassifier := protocolClassifier{
  513. minBytesToMatch: 4,
  514. maxBytesToMatch: 4,
  515. match: func(b []byte) bool {
  516. // NOTE: HTTP transforms are only applied to plain HTTP
  517. // meek so they are not a concern here.
  518. return bytes.Contains(b, []byte("POST"))
  519. },
  520. }
  521. tlsClassifier := protocolClassifier{
  522. // NOTE: technically +1 not needed if detectors are evaluated
  523. // in order by index in classifier array, which they are.
  524. minBytesToMatch: meekClassifier.maxBytesToMatch + 1,
  525. maxBytesToMatch: meekClassifier.maxBytesToMatch + 1,
  526. match: func(b []byte) bool {
  527. return len(b) > 4 // if not classified as meek, then tls
  528. },
  529. }
  530. listener, err := ListenTLSTunnel(
  531. sshServer.support,
  532. sshListener.Listener,
  533. sshListener.tunnelProtocol,
  534. sshListener.port)
  535. if err != nil {
  536. select {
  537. case listenerError <- errors.Trace(err):
  538. default:
  539. }
  540. return
  541. }
  542. mux, listeners := newProtocolDemux(
  543. context.Background(),
  544. listener,
  545. []protocolClassifier{meekClassifier, tlsClassifier},
  546. sshServer.support.Config.sshHandshakeTimeout)
  547. var wg sync.WaitGroup
  548. wg.Add(1)
  549. go func() {
  550. // handle shutdown gracefully
  551. defer wg.Done()
  552. <-sshServer.shutdownBroadcast
  553. err := mux.Close()
  554. if err != nil {
  555. log.WithTraceFields(LogFields{"error": err}).Error("close failed")
  556. }
  557. }()
  558. wg.Add(1)
  559. go func() {
  560. // start demultiplexing TLS-OSSH and meek HTTPS connections
  561. defer wg.Done()
  562. err := mux.run()
  563. if err != nil {
  564. select {
  565. case listenerError <- errors.Trace(err):
  566. default:
  567. }
  568. return
  569. }
  570. }()
  571. wg.Add(1)
  572. go func() {
  573. // start handling TLS-OSSH connections as they are demultiplexed
  574. defer wg.Done()
  575. // Override the listener tunnel protocol to report TLS-OSSH instead.
  576. runListener(
  577. listeners[1],
  578. sshServer.shutdownBroadcast,
  579. listenerError,
  580. protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH, handleClient)
  581. }()
  582. wg.Add(1)
  583. go func() {
  584. // start handling meek HTTPS connections as they are
  585. // demultiplexed
  586. defer wg.Done()
  587. meekServer, err := NewMeekServer(
  588. sshServer.support,
  589. listeners[0],
  590. sshListener.tunnelProtocol,
  591. sshListener.port,
  592. false,
  593. protocol.TunnelProtocolUsesFrontedMeek(sshListener.tunnelProtocol),
  594. protocol.TunnelProtocolUsesObfuscatedSessionTickets(sshListener.tunnelProtocol),
  595. true,
  596. handleClient,
  597. sshServer.shutdownBroadcast)
  598. if err == nil {
  599. sshServer.registerMeekServer(meekServer)
  600. err = meekServer.Run()
  601. }
  602. if err != nil {
  603. select {
  604. case listenerError <- errors.Trace(err):
  605. default:
  606. }
  607. return
  608. }
  609. }()
  610. wg.Wait()
  611. }
  612. func runListener(
  613. listener net.Listener,
  614. shutdownBroadcast <-chan struct{},
  615. listenerError chan<- error,
  616. overrideTunnelProtocol string,
  617. handleClient func(conn net.Conn, transportData *additionalTransportData)) {
  618. for {
  619. conn, err := listener.Accept()
  620. select {
  621. case <-shutdownBroadcast:
  622. if err == nil {
  623. conn.Close()
  624. }
  625. return
  626. default:
  627. }
  628. if err != nil {
  629. if e, ok := err.(net.Error); ok && e.Temporary() {
  630. log.WithTraceFields(LogFields{"error": err}).Error("accept failed")
  631. // Temporary error, keep running
  632. continue
  633. } else if std_errors.Is(err, errRestrictedProvider) {
  634. log.WithTraceFields(LogFields{"error": err}).Error("accept rejected client")
  635. // Restricted provider, keep running
  636. continue
  637. }
  638. select {
  639. case listenerError <- errors.Trace(err):
  640. default:
  641. }
  642. return
  643. }
  644. var transportData *additionalTransportData
  645. if overrideTunnelProtocol != "" {
  646. transportData = &additionalTransportData{
  647. overrideTunnelProtocol: overrideTunnelProtocol,
  648. }
  649. }
  650. handleClient(conn, transportData)
  651. }
  652. }
  653. // registerMeekServer registers a MeekServer instance to receive tactics
  654. // reload signals.
  655. func (sshServer *sshServer) registerMeekServer(meekServer *MeekServer) {
  656. sshServer.meekServersMutex.Lock()
  657. defer sshServer.meekServersMutex.Unlock()
  658. sshServer.meekServers = append(sshServer.meekServers, meekServer)
  659. }
  660. // reloadMeekServerTactics signals each registered MeekServer instance that
  661. // tactics have reloaded and may have changed.
  662. func (sshServer *sshServer) reloadMeekServerTactics() error {
  663. sshServer.meekServersMutex.Lock()
  664. defer sshServer.meekServersMutex.Unlock()
  665. for _, meekServer := range sshServer.meekServers {
  666. err := meekServer.ReloadTactics()
  667. if err != nil {
  668. return errors.Trace(err)
  669. }
  670. }
  671. return nil
  672. }
  673. // An accepted client has completed a direct TCP or meek connection and has a
  674. // net.Conn. Registration is for tracking the number of connections.
  675. func (sshServer *sshServer) registerAcceptedClient(tunnelProtocol, region string) {
  676. sshServer.clientsMutex.Lock()
  677. defer sshServer.clientsMutex.Unlock()
  678. if sshServer.acceptedClientCounts[tunnelProtocol] == nil {
  679. sshServer.acceptedClientCounts[tunnelProtocol] = make(map[string]int64)
  680. }
  681. sshServer.acceptedClientCounts[tunnelProtocol][region] += 1
  682. }
  683. func (sshServer *sshServer) unregisterAcceptedClient(tunnelProtocol, region string) {
  684. sshServer.clientsMutex.Lock()
  685. defer sshServer.clientsMutex.Unlock()
  686. sshServer.acceptedClientCounts[tunnelProtocol][region] -= 1
  687. }
  688. // An established client has completed its SSH handshake and has a ssh.Conn. Registration is
  689. // for tracking the number of fully established clients and for maintaining a list of running
  690. // clients (for stopping at shutdown time).
  691. func (sshServer *sshServer) registerEstablishedClient(client *sshClient) bool {
  692. sshServer.clientsMutex.Lock()
  693. if sshServer.stoppingClients {
  694. sshServer.clientsMutex.Unlock()
  695. return false
  696. }
  697. // In the case of a duplicate client sessionID, the previous client is closed.
  698. // - Well-behaved clients generate a random sessionID that should be unique (won't
  699. // accidentally conflict) and hard to guess (can't be targeted by a malicious
  700. // client).
  701. // - Clients reuse the same sessionID when a tunnel is unexpectedly disconnected
  702. // and reestablished. In this case, when the same server is selected, this logic
  703. // will be hit; closing the old, dangling client is desirable.
  704. // - Multi-tunnel clients should not normally use one server for multiple tunnels.
  705. existingClient := sshServer.clients[client.sessionID]
  706. sshServer.clientsMutex.Unlock()
  707. if existingClient != nil {
  708. // This case is expected to be common, and so logged at the lowest severity
  709. // level.
  710. log.WithTrace().Debug(
  711. "stopping existing client with duplicate session ID")
  712. existingClient.stop()
  713. // Block until the existingClient is fully terminated. This is necessary to
  714. // avoid this scenario:
  715. // - existingClient is invoking handshakeAPIRequestHandler
  716. // - sshServer.clients[client.sessionID] is updated to point to new client
  717. // - existingClient's handshakeAPIRequestHandler invokes
  718. // setHandshakeState but sets the handshake parameters for new
  719. // client
  720. // - as a result, the new client handshake will fail (only a single handshake
  721. // is permitted) and the new client server_tunnel log will contain an
  722. // invalid mix of existing/new client fields
  723. //
  724. // Once existingClient.awaitStopped returns, all existingClient port
  725. // forwards and request handlers have terminated, so no API handler, either
  726. // tunneled web API or SSH API, will remain and it is safe to point
  727. // sshServer.clients[client.sessionID] to the new client.
  728. // Limitation: this scenario remains possible with _untunneled_ web API
  729. // requests.
  730. //
  731. // Blocking also ensures existingClient.releaseAuthorizations is invoked before
  732. // the new client attempts to submit the same authorizations.
  733. //
  734. // Perform blocking awaitStopped operation outside the
  735. // sshServer.clientsMutex mutex to avoid blocking all other clients for the
  736. // duration. We still expect and require that the stop process completes
  737. // rapidly, e.g., does not block on network I/O, allowing the new client
  738. // connection to proceed without delay.
  739. //
  740. // In addition, operations triggered by stop, and which must complete before
  741. // awaitStopped returns, will attempt to lock sshServer.clientsMutex,
  742. // including unregisterEstablishedClient.
  743. existingClient.awaitStopped()
  744. }
  745. sshServer.clientsMutex.Lock()
  746. defer sshServer.clientsMutex.Unlock()
  747. // existingClient's stop will have removed it from sshServer.clients via
  748. // unregisterEstablishedClient, so sshServer.clients[client.sessionID] should
  749. // be nil -- unless yet another client instance using the same sessionID has
  750. // connected in the meantime while awaiting existingClient stop. In this
  751. // case, it's not clear which is the most recent connection from the client,
  752. // so instead of this connection terminating more peers, it aborts.
  753. if sshServer.clients[client.sessionID] != nil {
  754. // As this is expected to be rare case, it's logged at a higher severity
  755. // level.
  756. log.WithTrace().Warning(
  757. "aborting new client with duplicate session ID")
  758. return false
  759. }
  760. sshServer.clients[client.sessionID] = client
  761. return true
  762. }
  763. func (sshServer *sshServer) unregisterEstablishedClient(client *sshClient) {
  764. sshServer.clientsMutex.Lock()
  765. registeredClient := sshServer.clients[client.sessionID]
  766. // registeredClient will differ from client when client is the existingClient
  767. // terminated in registerEstablishedClient. In that case, registeredClient
  768. // remains connected, and the sshServer.clients entry should be retained.
  769. if registeredClient == client {
  770. delete(sshServer.clients, client.sessionID)
  771. }
  772. sshServer.clientsMutex.Unlock()
  773. client.stop()
  774. }
  775. type UpstreamStats map[string]interface{}
  776. type ProtocolStats map[string]map[string]interface{}
  777. type RegionStats map[string]map[string]map[string]interface{}
  778. func (sshServer *sshServer) getLoadStats() (
  779. UpstreamStats, ProtocolStats, RegionStats) {
  780. sshServer.clientsMutex.Lock()
  781. defer sshServer.clientsMutex.Unlock()
  782. // Explicitly populate with zeros to ensure 0 counts in log messages.
  783. zeroClientStats := func() map[string]interface{} {
  784. stats := make(map[string]interface{})
  785. stats["accepted_clients"] = int64(0)
  786. stats["established_clients"] = int64(0)
  787. return stats
  788. }
  789. // Due to hot reload and changes to the underlying system configuration, the
  790. // set of resolver IPs may change between getLoadStats calls, so this
  791. // enumeration for zeroing is a best effort.
  792. resolverIPs := sshServer.support.DNSResolver.GetAll()
  793. // Fields which are primarily concerned with upstream/egress performance.
  794. zeroUpstreamStats := func() map[string]interface{} {
  795. stats := make(map[string]interface{})
  796. stats["dialing_tcp_port_forwards"] = int64(0)
  797. stats["tcp_port_forwards"] = int64(0)
  798. stats["total_tcp_port_forwards"] = int64(0)
  799. stats["udp_port_forwards"] = int64(0)
  800. stats["total_udp_port_forwards"] = int64(0)
  801. stats["tcp_port_forward_dialed_count"] = int64(0)
  802. stats["tcp_port_forward_dialed_duration"] = int64(0)
  803. stats["tcp_port_forward_failed_count"] = int64(0)
  804. stats["tcp_port_forward_failed_duration"] = int64(0)
  805. stats["tcp_port_forward_rejected_dialing_limit_count"] = int64(0)
  806. stats["tcp_port_forward_rejected_disallowed_count"] = int64(0)
  807. stats["udp_port_forward_rejected_disallowed_count"] = int64(0)
  808. stats["tcp_ipv4_port_forward_dialed_count"] = int64(0)
  809. stats["tcp_ipv4_port_forward_dialed_duration"] = int64(0)
  810. stats["tcp_ipv4_port_forward_failed_count"] = int64(0)
  811. stats["tcp_ipv4_port_forward_failed_duration"] = int64(0)
  812. stats["tcp_ipv6_port_forward_dialed_count"] = int64(0)
  813. stats["tcp_ipv6_port_forward_dialed_duration"] = int64(0)
  814. stats["tcp_ipv6_port_forward_failed_count"] = int64(0)
  815. stats["tcp_ipv6_port_forward_failed_duration"] = int64(0)
  816. zeroDNSStats := func() map[string]int64 {
  817. m := map[string]int64{"ALL": 0}
  818. for _, resolverIP := range resolverIPs {
  819. m[resolverIP.String()] = 0
  820. }
  821. return m
  822. }
  823. stats["dns_count"] = zeroDNSStats()
  824. stats["dns_duration"] = zeroDNSStats()
  825. stats["dns_failed_count"] = zeroDNSStats()
  826. stats["dns_failed_duration"] = zeroDNSStats()
  827. return stats
  828. }
  829. zeroProtocolStats := func() map[string]map[string]interface{} {
  830. stats := make(map[string]map[string]interface{})
  831. stats["ALL"] = zeroClientStats()
  832. for tunnelProtocol := range sshServer.support.Config.TunnelProtocolPorts {
  833. stats[tunnelProtocol] = zeroClientStats()
  834. if sshServer.tunnelProtocolUsesTLSDemux(tunnelProtocol) {
  835. stats[protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH] = zeroClientStats()
  836. }
  837. }
  838. return stats
  839. }
  840. addInt64 := func(stats map[string]interface{}, name string, value int64) {
  841. stats[name] = stats[name].(int64) + value
  842. }
  843. upstreamStats := zeroUpstreamStats()
  844. // [<protocol or ALL>][<stat name>] -> count
  845. protocolStats := zeroProtocolStats()
  846. // [<region][<protocol or ALL>][<stat name>] -> count
  847. regionStats := make(RegionStats)
  848. // Note: as currently tracked/counted, each established client is also an accepted client
  849. // Accepted client counts use peer GeoIP data, which in the case of
  850. // in-proxy tunnel protocols is the proxy, not the client. The original
  851. // client IP is only obtained after the tunnel handshake has completed.
  852. for tunnelProtocol, regionAcceptedClientCounts := range sshServer.acceptedClientCounts {
  853. for region, acceptedClientCount := range regionAcceptedClientCounts {
  854. if acceptedClientCount > 0 {
  855. if regionStats[region] == nil {
  856. regionStats[region] = zeroProtocolStats()
  857. }
  858. addInt64(protocolStats["ALL"], "accepted_clients", acceptedClientCount)
  859. addInt64(protocolStats[tunnelProtocol], "accepted_clients", acceptedClientCount)
  860. addInt64(regionStats[region]["ALL"], "accepted_clients", acceptedClientCount)
  861. addInt64(regionStats[region][tunnelProtocol], "accepted_clients", acceptedClientCount)
  862. }
  863. }
  864. }
  865. for _, client := range sshServer.clients {
  866. client.Lock()
  867. // Limitation: registerEstablishedClient is called before the
  868. // handshake API completes; as a result, in the case of in-proxy
  869. // tunnel protocol, clientGeoIPData may not yet be initialized and
  870. // will count as None.
  871. tunnelProtocol := client.tunnelProtocol
  872. region := client.clientGeoIPData.Country
  873. if regionStats[region] == nil {
  874. regionStats[region] = zeroProtocolStats()
  875. }
  876. for _, stats := range []map[string]interface{}{
  877. protocolStats["ALL"],
  878. protocolStats[tunnelProtocol],
  879. regionStats[region]["ALL"],
  880. regionStats[region][tunnelProtocol]} {
  881. addInt64(stats, "established_clients", 1)
  882. }
  883. // Note:
  884. // - can't sum trafficState.peakConcurrentPortForwardCount to get a global peak
  885. // - client.udpTrafficState.concurrentDialingPortForwardCount isn't meaningful
  886. addInt64(upstreamStats, "dialing_tcp_port_forwards",
  887. client.tcpTrafficState.concurrentDialingPortForwardCount)
  888. addInt64(upstreamStats, "tcp_port_forwards",
  889. client.tcpTrafficState.concurrentPortForwardCount)
  890. addInt64(upstreamStats, "total_tcp_port_forwards",
  891. client.tcpTrafficState.totalPortForwardCount)
  892. addInt64(upstreamStats, "udp_port_forwards",
  893. client.udpTrafficState.concurrentPortForwardCount)
  894. addInt64(upstreamStats, "total_udp_port_forwards",
  895. client.udpTrafficState.totalPortForwardCount)
  896. addInt64(upstreamStats, "tcp_port_forward_dialed_count",
  897. client.qualityMetrics.TCPPortForwardDialedCount)
  898. addInt64(upstreamStats, "tcp_port_forward_dialed_duration",
  899. int64(client.qualityMetrics.TCPPortForwardDialedDuration/time.Millisecond))
  900. addInt64(upstreamStats, "tcp_port_forward_failed_count",
  901. client.qualityMetrics.TCPPortForwardFailedCount)
  902. addInt64(upstreamStats, "tcp_port_forward_failed_duration",
  903. int64(client.qualityMetrics.TCPPortForwardFailedDuration/time.Millisecond))
  904. addInt64(upstreamStats, "tcp_port_forward_rejected_dialing_limit_count",
  905. client.qualityMetrics.TCPPortForwardRejectedDialingLimitCount)
  906. addInt64(upstreamStats, "tcp_port_forward_rejected_disallowed_count",
  907. client.qualityMetrics.TCPPortForwardRejectedDisallowedCount)
  908. addInt64(upstreamStats, "udp_port_forward_rejected_disallowed_count",
  909. client.qualityMetrics.UDPPortForwardRejectedDisallowedCount)
  910. addInt64(upstreamStats, "tcp_ipv4_port_forward_dialed_count",
  911. client.qualityMetrics.TCPIPv4PortForwardDialedCount)
  912. addInt64(upstreamStats, "tcp_ipv4_port_forward_dialed_duration",
  913. int64(client.qualityMetrics.TCPIPv4PortForwardDialedDuration/time.Millisecond))
  914. addInt64(upstreamStats, "tcp_ipv4_port_forward_failed_count",
  915. client.qualityMetrics.TCPIPv4PortForwardFailedCount)
  916. addInt64(upstreamStats, "tcp_ipv4_port_forward_failed_duration",
  917. int64(client.qualityMetrics.TCPIPv4PortForwardFailedDuration/time.Millisecond))
  918. addInt64(upstreamStats, "tcp_ipv6_port_forward_dialed_count",
  919. client.qualityMetrics.TCPIPv6PortForwardDialedCount)
  920. addInt64(upstreamStats, "tcp_ipv6_port_forward_dialed_duration",
  921. int64(client.qualityMetrics.TCPIPv6PortForwardDialedDuration/time.Millisecond))
  922. addInt64(upstreamStats, "tcp_ipv6_port_forward_failed_count",
  923. client.qualityMetrics.TCPIPv6PortForwardFailedCount)
  924. addInt64(upstreamStats, "tcp_ipv6_port_forward_failed_duration",
  925. int64(client.qualityMetrics.TCPIPv6PortForwardFailedDuration/time.Millisecond))
  926. // DNS metrics limitations:
  927. // - port forwards (sshClient.handleTCPChannel) don't know or log the resolver IP.
  928. // - udpgw and packet tunnel transparent DNS use a heuristic to classify success/failure,
  929. // and there may be some delay before these code paths report DNS metrics.
  930. // Every client.qualityMetrics DNS map has an "ALL" entry.
  931. totalDNSCount := int64(0)
  932. totalDNSFailedCount := int64(0)
  933. for key, value := range client.qualityMetrics.DNSCount {
  934. upstreamStats["dns_count"].(map[string]int64)[key] += value
  935. totalDNSCount += value
  936. }
  937. for key, value := range client.qualityMetrics.DNSDuration {
  938. upstreamStats["dns_duration"].(map[string]int64)[key] += int64(value / time.Millisecond)
  939. }
  940. for key, value := range client.qualityMetrics.DNSFailedCount {
  941. upstreamStats["dns_failed_count"].(map[string]int64)[key] += value
  942. totalDNSFailedCount += value
  943. }
  944. for key, value := range client.qualityMetrics.DNSFailedDuration {
  945. upstreamStats["dns_failed_duration"].(map[string]int64)[key] += int64(value / time.Millisecond)
  946. }
  947. // Update client peak failure rate metrics, to be recorded in
  948. // server_tunnel.
  949. //
  950. // Limitations:
  951. //
  952. // - This is a simple data sampling that doesn't require additional
  953. // timers or tracking logic. Since the rates are calculated on
  954. // getLoadStats events and using accumulated counts, these peaks
  955. // only represent the highest failure rate within a
  956. // Config.LoadMonitorPeriodSeconds non-sliding window. There is no
  957. // sample recorded for short tunnels with no overlapping
  958. // getLoadStats event.
  959. //
  960. // - There is no minimum sample window, as a getLoadStats event may
  961. // occur immediately after a client first connects. This may be
  962. // compensated for by adjusting
  963. // Config.PeakUpstreamFailureRateMinimumSampleSize, so as to only
  964. // consider failure rates with a larger number of samples.
  965. //
  966. // - Non-UDP "failures" are not currently tracked.
  967. minimumSampleSize := int64(sshServer.support.Config.peakUpstreamFailureRateMinimumSampleSize)
  968. sampleSize := client.qualityMetrics.TCPPortForwardDialedCount +
  969. client.qualityMetrics.TCPPortForwardFailedCount
  970. if sampleSize >= minimumSampleSize {
  971. TCPPortForwardFailureRate := float64(client.qualityMetrics.TCPPortForwardFailedCount) /
  972. float64(sampleSize)
  973. if client.peakMetrics.TCPPortForwardFailureRate == nil {
  974. client.peakMetrics.TCPPortForwardFailureRate = new(float64)
  975. *client.peakMetrics.TCPPortForwardFailureRate = TCPPortForwardFailureRate
  976. client.peakMetrics.TCPPortForwardFailureRateSampleSize = new(int64)
  977. *client.peakMetrics.TCPPortForwardFailureRateSampleSize = sampleSize
  978. } else if *client.peakMetrics.TCPPortForwardFailureRate < TCPPortForwardFailureRate {
  979. *client.peakMetrics.TCPPortForwardFailureRate = TCPPortForwardFailureRate
  980. *client.peakMetrics.TCPPortForwardFailureRateSampleSize = sampleSize
  981. }
  982. }
  983. sampleSize = totalDNSCount + totalDNSFailedCount
  984. if sampleSize >= minimumSampleSize {
  985. DNSFailureRate := float64(totalDNSFailedCount) / float64(sampleSize)
  986. if client.peakMetrics.DNSFailureRate == nil {
  987. client.peakMetrics.DNSFailureRate = new(float64)
  988. *client.peakMetrics.DNSFailureRate = DNSFailureRate
  989. client.peakMetrics.DNSFailureRateSampleSize = new(int64)
  990. *client.peakMetrics.DNSFailureRateSampleSize = sampleSize
  991. } else if *client.peakMetrics.DNSFailureRate < DNSFailureRate {
  992. *client.peakMetrics.DNSFailureRate = DNSFailureRate
  993. *client.peakMetrics.DNSFailureRateSampleSize = sampleSize
  994. }
  995. }
  996. // Reset quality metrics counters
  997. client.qualityMetrics.reset()
  998. client.Unlock()
  999. }
  1000. for _, client := range sshServer.clients {
  1001. client.Lock()
  1002. // Update client peak proximate (same region) concurrently connected
  1003. // (other clients) client metrics, to be recorded in server_tunnel.
  1004. // This operation requires a second loop over sshServer.clients since
  1005. // established_clients is calculated in the first loop.
  1006. //
  1007. // Limitations:
  1008. //
  1009. // - This is an approximation, not a true peak, as it only samples
  1010. // data every Config.LoadMonitorPeriodSeconds period. There is no
  1011. // sample recorded for short tunnels with no overlapping
  1012. // getLoadStats event.
  1013. //
  1014. // - The "-1" calculation counts all but the current client as other
  1015. // clients; it can be the case that the same client has a dangling
  1016. // accepted connection that has yet to time-out server side. Due to
  1017. // NAT, we can't determine if the client is the same based on
  1018. // network address. For established clients,
  1019. // registerEstablishedClient ensures that any previous connection
  1020. // is first terminated, although this is only for the same
  1021. // session_id. Concurrent proximate clients may be considered an
  1022. // exact number of other _network connections_, even from the same
  1023. // client.
  1024. //
  1025. // - For in-proxy tunnel protocols, the same GeoIP caveats
  1026. // (see comments above) apply.
  1027. stats := regionStats[client.peerGeoIPData.Country]["ALL"]
  1028. n := stats["accepted_clients"].(int64) - 1
  1029. if n >= 0 {
  1030. if client.peakMetrics.concurrentProximateAcceptedClients == nil {
  1031. client.peakMetrics.concurrentProximateAcceptedClients = new(int64)
  1032. *client.peakMetrics.concurrentProximateAcceptedClients = n
  1033. } else if *client.peakMetrics.concurrentProximateAcceptedClients < n {
  1034. *client.peakMetrics.concurrentProximateAcceptedClients = n
  1035. }
  1036. }
  1037. stats = regionStats[client.clientGeoIPData.Country]["ALL"]
  1038. n = stats["established_clients"].(int64) - 1
  1039. if n >= 0 {
  1040. if client.peakMetrics.concurrentProximateEstablishedClients == nil {
  1041. client.peakMetrics.concurrentProximateEstablishedClients = new(int64)
  1042. *client.peakMetrics.concurrentProximateEstablishedClients = n
  1043. } else if *client.peakMetrics.concurrentProximateEstablishedClients < n {
  1044. *client.peakMetrics.concurrentProximateEstablishedClients = n
  1045. }
  1046. }
  1047. client.Unlock()
  1048. }
  1049. return upstreamStats, protocolStats, regionStats
  1050. }
  1051. func (sshServer *sshServer) getEstablishedClientCount() int {
  1052. sshServer.clientsMutex.Lock()
  1053. defer sshServer.clientsMutex.Unlock()
  1054. establishedClients := len(sshServer.clients)
  1055. return establishedClients
  1056. }
  1057. func (sshServer *sshServer) resetAllClientTrafficRules() {
  1058. sshServer.clientsMutex.Lock()
  1059. clients := make(map[string]*sshClient)
  1060. for sessionID, client := range sshServer.clients {
  1061. clients[sessionID] = client
  1062. }
  1063. sshServer.clientsMutex.Unlock()
  1064. for _, client := range clients {
  1065. client.setTrafficRules()
  1066. }
  1067. }
  1068. func (sshServer *sshServer) resetAllClientOSLConfigs() {
  1069. // Flush cached seed state. This has the same effect
  1070. // and same limitations as calling setOSLConfig for
  1071. // currently connected clients -- all progress is lost.
  1072. sshServer.oslSessionCacheMutex.Lock()
  1073. sshServer.oslSessionCache.Flush()
  1074. sshServer.oslSessionCacheMutex.Unlock()
  1075. sshServer.clientsMutex.Lock()
  1076. clients := make(map[string]*sshClient)
  1077. for sessionID, client := range sshServer.clients {
  1078. clients[sessionID] = client
  1079. }
  1080. sshServer.clientsMutex.Unlock()
  1081. for _, client := range clients {
  1082. client.setOSLConfig()
  1083. }
  1084. }
  1085. // reloadTactics signals/invokes components that use server-side tactics for
  1086. // one-time initialization to reload and use potentially changed parameters.
  1087. func (sshServer *sshServer) reloadTactics() error {
  1088. // The following in-proxy components use server-side tactics with a
  1089. // one-time initialization:
  1090. //
  1091. // - For servers running in-proxy tunnel protocols,
  1092. // sshServer.inproxyBrokerSessions are the broker/server sessions and
  1093. // the set of expected broker public keys is set from tactics.
  1094. // - For servers running a broker within MeekServer, broker operational
  1095. // configuration is set from tactics.
  1096. //
  1097. // For these components, one-time initialization is more efficient than
  1098. // constantly fetching tactics. Instead, these components reinitialize
  1099. // when tactics change.
  1100. // sshServer.inproxyBrokerSessions is not nil when the server is running
  1101. // in-proxy tunnel protocols.
  1102. if sshServer.inproxyBrokerSessions != nil {
  1103. // Get InproxyAllBrokerPublicKeys from tactics.
  1104. //
  1105. // Limitation: assumes no GeoIP targeting for InproxyAllBrokerPublicKeys.
  1106. p, err := sshServer.support.ServerTacticsParametersCache.Get(NewGeoIPData())
  1107. if err != nil {
  1108. return errors.Trace(err)
  1109. }
  1110. if !p.IsNil() {
  1111. brokerPublicKeys, err := inproxy.SessionPublicKeysFromStrings(
  1112. p.Strings(parameters.InproxyAllBrokerPublicKeys))
  1113. if err != nil {
  1114. return errors.Trace(err)
  1115. }
  1116. // SetKnownBrokerPublicKeys will terminate any existing sessions
  1117. // for broker public keys no longer in the known/expected list;
  1118. // but will retain any existing sessions for broker public keys
  1119. // that remain in the list.
  1120. sshServer.inproxyBrokerSessions.SetKnownBrokerPublicKeys(brokerPublicKeys)
  1121. }
  1122. }
  1123. err := sshServer.reloadMeekServerTactics()
  1124. if err != nil {
  1125. return errors.Trace(err)
  1126. }
  1127. return nil
  1128. }
  1129. func (sshServer *sshServer) revokeClientAuthorizations(sessionID string) {
  1130. sshServer.clientsMutex.Lock()
  1131. client := sshServer.clients[sessionID]
  1132. sshServer.clientsMutex.Unlock()
  1133. if client == nil {
  1134. return
  1135. }
  1136. // sshClient.handshakeState.authorizedAccessTypes is not cleared. Clearing
  1137. // authorizedAccessTypes may cause sshClient.logTunnel to fail to log
  1138. // access types. As the revocation may be due to legitimate use of an
  1139. // authorization in multiple sessions by a single client, useful metrics
  1140. // would be lost.
  1141. client.Lock()
  1142. client.handshakeState.authorizationsRevoked = true
  1143. client.Unlock()
  1144. // Select and apply new traffic rules, as filtered by the client's new
  1145. // authorization state.
  1146. client.setTrafficRules()
  1147. }
  1148. func (sshServer *sshServer) stopClients() {
  1149. sshServer.clientsMutex.Lock()
  1150. sshServer.stoppingClients = true
  1151. clients := sshServer.clients
  1152. sshServer.clients = make(map[string]*sshClient)
  1153. sshServer.clientsMutex.Unlock()
  1154. for _, client := range clients {
  1155. client.stop()
  1156. }
  1157. }
  1158. func (sshServer *sshServer) handleClient(
  1159. sshListener *sshListener,
  1160. conn net.Conn,
  1161. transportData *additionalTransportData) {
  1162. // overrideTunnelProtocol sets the tunnel protocol to a value other than
  1163. // the listener tunnel protocol. This is used in fronted meek
  1164. // configuration, where a single HTTPS listener also handles fronted HTTP
  1165. // and QUIC traffic; and in the protocol demux case.
  1166. tunnelProtocol := sshListener.tunnelProtocol
  1167. if transportData != nil && transportData.overrideTunnelProtocol != "" {
  1168. tunnelProtocol = transportData.overrideTunnelProtocol
  1169. }
  1170. // Calling conn.RemoteAddr at this point, before any Read calls,
  1171. // satisfies the constraint documented in tapdance.Listen.
  1172. peerAddr := conn.RemoteAddr()
  1173. // Check if there were irregularities during the network connection
  1174. // establishment. When present, log and then behave as Obfuscated SSH does
  1175. // when the client fails to provide a valid seed message.
  1176. //
  1177. // One concrete irregular case is failure to send a PROXY protocol header for
  1178. // TAPDANCE-OSSH.
  1179. if indicator, ok := conn.(common.IrregularIndicator); ok {
  1180. tunnelErr := indicator.IrregularTunnelError()
  1181. if tunnelErr != nil {
  1182. logIrregularTunnel(
  1183. sshServer.support,
  1184. sshListener.tunnelProtocol,
  1185. sshListener.port,
  1186. common.IPAddressFromAddr(peerAddr),
  1187. errors.Trace(tunnelErr),
  1188. nil)
  1189. var afterFunc *time.Timer
  1190. if sshServer.support.Config.sshHandshakeTimeout > 0 {
  1191. afterFunc = time.AfterFunc(sshServer.support.Config.sshHandshakeTimeout, func() {
  1192. conn.Close()
  1193. })
  1194. }
  1195. io.Copy(ioutil.Discard, conn)
  1196. conn.Close()
  1197. afterFunc.Stop()
  1198. return
  1199. }
  1200. }
  1201. // Get any packet manipulation values from GetAppliedSpecName as soon as
  1202. // possible due to the expiring TTL.
  1203. //
  1204. // In the case of in-proxy tunnel protocols, the remote address will be
  1205. // the proxy, not the client, and GeoIP targeted packet manipulation will
  1206. // apply to the 2nd hop.
  1207. serverPacketManipulation := ""
  1208. replayedServerPacketManipulation := false
  1209. if sshServer.support.Config.RunPacketManipulator &&
  1210. protocol.TunnelProtocolMayUseServerPacketManipulation(tunnelProtocol) {
  1211. // A meekConn has synthetic address values, including the original client
  1212. // address in cases where the client uses an upstream proxy to connect to
  1213. // Psiphon. For meekConn, and any other conn implementing
  1214. // UnderlyingTCPAddrSource, get the underlying TCP connection addresses.
  1215. //
  1216. // Limitation: a meek tunnel may consist of several TCP connections. The
  1217. // server_packet_manipulation metric will reflect the packet manipulation
  1218. // applied to the _first_ TCP connection only.
  1219. var localAddr, remoteAddr *net.TCPAddr
  1220. var ok bool
  1221. underlying, ok := conn.(common.UnderlyingTCPAddrSource)
  1222. if ok {
  1223. localAddr, remoteAddr, ok = underlying.GetUnderlyingTCPAddrs()
  1224. } else {
  1225. localAddr, ok = conn.LocalAddr().(*net.TCPAddr)
  1226. if ok {
  1227. remoteAddr, ok = conn.RemoteAddr().(*net.TCPAddr)
  1228. }
  1229. }
  1230. if ok {
  1231. specName, extraData, err := sshServer.support.PacketManipulator.
  1232. GetAppliedSpecName(localAddr, remoteAddr)
  1233. if err == nil {
  1234. serverPacketManipulation = specName
  1235. replayedServerPacketManipulation, _ = extraData.(bool)
  1236. }
  1237. }
  1238. }
  1239. // For in-proxy tunnel protocols, accepted client GeoIP reflects the proxy
  1240. // address, not the client.
  1241. peerGeoIPData := sshServer.support.GeoIPService.Lookup(
  1242. common.IPAddressFromAddr(peerAddr))
  1243. sshServer.registerAcceptedClient(tunnelProtocol, peerGeoIPData.Country)
  1244. defer sshServer.unregisterAcceptedClient(tunnelProtocol, peerGeoIPData.Country)
  1245. // When configured, enforce a cap on the number of concurrent SSH
  1246. // handshakes. This limits load spikes on busy servers when many clients
  1247. // attempt to connect at once. Wait a short time, SSH_BEGIN_HANDSHAKE_TIMEOUT,
  1248. // to acquire; waiting will avoid immediately creating more load on another
  1249. // server in the network when the client tries a new candidate. Disconnect the
  1250. // client when that wait time is exceeded.
  1251. //
  1252. // This mechanism limits memory allocations and CPU usage associated with the
  1253. // SSH handshake. At this point, new direct TCP connections or new meek
  1254. // connections, with associated resource usage, are already established. Those
  1255. // connections are expected to be rate or load limited using other mechanisms.
  1256. //
  1257. // TODO:
  1258. //
  1259. // - deduct time spent acquiring the semaphore from SSH_HANDSHAKE_TIMEOUT in
  1260. // sshClient.run, since the client is also applying an SSH handshake timeout
  1261. // and won't exclude time spent waiting.
  1262. // - each call to sshServer.handleClient (in sshServer.runListener) is invoked
  1263. // in its own goroutine, but shutdown doesn't synchronously await these
  1264. // goroutnes. Once this is synchronizes, the following context.WithTimeout
  1265. // should use an sshServer parent context to ensure blocking acquires
  1266. // interrupt immediately upon shutdown.
  1267. var onSSHHandshakeFinished func()
  1268. if sshServer.support.Config.MaxConcurrentSSHHandshakes > 0 {
  1269. ctx, cancelFunc := context.WithTimeout(
  1270. context.Background(),
  1271. sshServer.support.Config.sshBeginHandshakeTimeout)
  1272. defer cancelFunc()
  1273. err := sshServer.concurrentSSHHandshakes.Acquire(ctx, 1)
  1274. if err != nil {
  1275. conn.Close()
  1276. // This is a debug log as the only possible error is context timeout.
  1277. log.WithTraceFields(LogFields{"error": err}).Debug(
  1278. "acquire SSH handshake semaphore failed")
  1279. return
  1280. }
  1281. onSSHHandshakeFinished = func() {
  1282. sshServer.concurrentSSHHandshakes.Release(1)
  1283. }
  1284. }
  1285. sshClient := newSshClient(
  1286. sshServer,
  1287. sshListener,
  1288. tunnelProtocol,
  1289. transportData,
  1290. serverPacketManipulation,
  1291. replayedServerPacketManipulation,
  1292. peerAddr,
  1293. peerGeoIPData)
  1294. // sshClient.run _must_ call onSSHHandshakeFinished to release the semaphore:
  1295. // in any error case; or, as soon as the SSH handshake phase has successfully
  1296. // completed.
  1297. sshClient.run(conn, onSSHHandshakeFinished)
  1298. }
  1299. func (sshServer *sshServer) monitorPortForwardDialError(err error) {
  1300. // "err" is the error returned from a failed TCP or UDP port
  1301. // forward dial. Certain system error codes indicate low resource
  1302. // conditions: insufficient file descriptors, ephemeral ports, or
  1303. // memory. For these cases, log an alert.
  1304. // TODO: also temporarily suspend new clients
  1305. // Note: don't log net.OpError.Error() as the full error string
  1306. // may contain client destination addresses.
  1307. opErr, ok := err.(*net.OpError)
  1308. if ok {
  1309. if opErr.Err == syscall.EADDRNOTAVAIL ||
  1310. opErr.Err == syscall.EAGAIN ||
  1311. opErr.Err == syscall.ENOMEM ||
  1312. opErr.Err == syscall.EMFILE ||
  1313. opErr.Err == syscall.ENFILE {
  1314. log.WithTraceFields(
  1315. LogFields{"error": opErr.Err}).Error(
  1316. "port forward dial failed due to unavailable resource")
  1317. }
  1318. }
  1319. }
  1320. // tunnelProtocolUsesTLSDemux returns true if the server demultiplexes the given
  1321. // protocol and TLS-OSSH over the same port.
  1322. func (sshServer *sshServer) tunnelProtocolUsesTLSDemux(tunnelProtocol string) bool {
  1323. // Only use meek/TLS-OSSH demux if unfronted meek HTTPS with non-legacy
  1324. // passthrough, and not in-proxy.
  1325. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) &&
  1326. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) &&
  1327. !protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  1328. _, passthroughEnabled := sshServer.support.Config.TunnelProtocolPassthroughAddresses[tunnelProtocol]
  1329. return passthroughEnabled && !sshServer.support.Config.LegacyPassthrough
  1330. }
  1331. return false
  1332. }
  1333. // setGeoIPSessionCache adds the sessionID/geoIPData pair to the session
  1334. // cache. This value will not expire; the caller must call
  1335. // markGeoIPSessionCacheToExpire to initiate expiry. Calling
  1336. // setGeoIPSessionCache for an existing sessionID will replace the previous
  1337. // value and reset any expiry.
  1338. func (sshServer *sshServer) setGeoIPSessionCache(sessionID string, geoIPData GeoIPData) {
  1339. sshServer.geoIPSessionCache.Set(sessionID, geoIPData, cache.NoExpiration)
  1340. }
  1341. // markGeoIPSessionCacheToExpire initiates expiry for an existing session
  1342. // cache entry, if the session ID is found in the cache. Concurrency note:
  1343. // setGeoIPSessionCache and markGeoIPSessionCacheToExpire should not be
  1344. // called concurrently for a single session ID.
  1345. func (sshServer *sshServer) markGeoIPSessionCacheToExpire(sessionID string) {
  1346. geoIPData, found := sshServer.geoIPSessionCache.Get(sessionID)
  1347. // Note: potential race condition between Get and Set. In practice,
  1348. // the tunnel server won't clobber a SetSessionCache value by calling
  1349. // MarkSessionCacheToExpire concurrently.
  1350. if found {
  1351. sshServer.geoIPSessionCache.Set(sessionID, geoIPData, cache.DefaultExpiration)
  1352. }
  1353. }
  1354. // getGeoIPSessionCache returns the cached GeoIPData for the specified session
  1355. // ID; a blank GeoIPData is returned if the session ID is not found in the
  1356. // cache.
  1357. func (sshServer *sshServer) getGeoIPSessionCache(sessionID string) GeoIPData {
  1358. geoIPData, found := sshServer.geoIPSessionCache.Get(sessionID)
  1359. if !found {
  1360. return NewGeoIPData()
  1361. }
  1362. return geoIPData.(GeoIPData)
  1363. }
  1364. // inGeoIPSessionCache returns whether the session ID is present in the
  1365. // session cache.
  1366. func (sshServer *sshServer) inGeoIPSessionCache(sessionID string) bool {
  1367. _, found := sshServer.geoIPSessionCache.Get(sessionID)
  1368. return found
  1369. }
  1370. type sshClient struct {
  1371. sync.Mutex
  1372. sshServer *sshServer
  1373. sshListener *sshListener
  1374. tunnelProtocol string
  1375. isInproxyTunnelProtocol bool
  1376. additionalTransportData *additionalTransportData
  1377. sshConn ssh.Conn
  1378. throttledConn *common.ThrottledConn
  1379. serverPacketManipulation string
  1380. replayedServerPacketManipulation bool
  1381. peerAddr net.Addr
  1382. peerGeoIPData GeoIPData
  1383. clientGeoIPData GeoIPData
  1384. sessionID string
  1385. isFirstTunnelInSession bool
  1386. supportsServerRequests bool
  1387. handshakeState handshakeState
  1388. udpgwChannelHandler *udpgwPortForwardMultiplexer
  1389. totalUdpgwChannelCount int
  1390. packetTunnelChannel ssh.Channel
  1391. totalPacketTunnelChannelCount int
  1392. trafficRules TrafficRules
  1393. tcpTrafficState trafficState
  1394. udpTrafficState trafficState
  1395. qualityMetrics *qualityMetrics
  1396. tcpPortForwardLRU *common.LRUConns
  1397. oslClientSeedState *osl.ClientSeedState
  1398. signalIssueSLOKs chan struct{}
  1399. runCtx context.Context
  1400. stopRunning context.CancelFunc
  1401. stopped chan struct{}
  1402. tcpPortForwardDialingAvailableSignal context.CancelFunc
  1403. releaseAuthorizations func()
  1404. stopTimer *time.Timer
  1405. preHandshakeRandomStreamMetrics randomStreamMetrics
  1406. postHandshakeRandomStreamMetrics randomStreamMetrics
  1407. sendAlertRequests chan protocol.AlertRequest
  1408. sentAlertRequests map[string]bool
  1409. peakMetrics peakMetrics
  1410. destinationBytesMetricsASN string
  1411. tcpDestinationBytesMetrics destinationBytesMetrics
  1412. udpDestinationBytesMetrics destinationBytesMetrics
  1413. }
  1414. type trafficState struct {
  1415. bytesUp int64
  1416. bytesDown int64
  1417. concurrentDialingPortForwardCount int64
  1418. peakConcurrentDialingPortForwardCount int64
  1419. concurrentPortForwardCount int64
  1420. peakConcurrentPortForwardCount int64
  1421. totalPortForwardCount int64
  1422. availablePortForwardCond *sync.Cond
  1423. }
  1424. type randomStreamMetrics struct {
  1425. count int64
  1426. upstreamBytes int64
  1427. receivedUpstreamBytes int64
  1428. downstreamBytes int64
  1429. sentDownstreamBytes int64
  1430. }
  1431. type peakMetrics struct {
  1432. concurrentProximateAcceptedClients *int64
  1433. concurrentProximateEstablishedClients *int64
  1434. TCPPortForwardFailureRate *float64
  1435. TCPPortForwardFailureRateSampleSize *int64
  1436. DNSFailureRate *float64
  1437. DNSFailureRateSampleSize *int64
  1438. }
  1439. // qualityMetrics records upstream TCP dial attempts and
  1440. // elapsed time. Elapsed time includes the full TCP handshake
  1441. // and, in aggregate, is a measure of the quality of the
  1442. // upstream link. These stats are recorded by each sshClient
  1443. // and then reported and reset in sshServer.getLoadStats().
  1444. type qualityMetrics struct {
  1445. TCPPortForwardDialedCount int64
  1446. TCPPortForwardDialedDuration time.Duration
  1447. TCPPortForwardFailedCount int64
  1448. TCPPortForwardFailedDuration time.Duration
  1449. TCPPortForwardRejectedDialingLimitCount int64
  1450. TCPPortForwardRejectedDisallowedCount int64
  1451. UDPPortForwardRejectedDisallowedCount int64
  1452. TCPIPv4PortForwardDialedCount int64
  1453. TCPIPv4PortForwardDialedDuration time.Duration
  1454. TCPIPv4PortForwardFailedCount int64
  1455. TCPIPv4PortForwardFailedDuration time.Duration
  1456. TCPIPv6PortForwardDialedCount int64
  1457. TCPIPv6PortForwardDialedDuration time.Duration
  1458. TCPIPv6PortForwardFailedCount int64
  1459. TCPIPv6PortForwardFailedDuration time.Duration
  1460. DNSCount map[string]int64
  1461. DNSDuration map[string]time.Duration
  1462. DNSFailedCount map[string]int64
  1463. DNSFailedDuration map[string]time.Duration
  1464. }
  1465. func newQualityMetrics() *qualityMetrics {
  1466. return &qualityMetrics{
  1467. DNSCount: make(map[string]int64),
  1468. DNSDuration: make(map[string]time.Duration),
  1469. DNSFailedCount: make(map[string]int64),
  1470. DNSFailedDuration: make(map[string]time.Duration),
  1471. }
  1472. }
  1473. func (q *qualityMetrics) reset() {
  1474. q.TCPPortForwardDialedCount = 0
  1475. q.TCPPortForwardDialedDuration = 0
  1476. q.TCPPortForwardFailedCount = 0
  1477. q.TCPPortForwardFailedDuration = 0
  1478. q.TCPPortForwardRejectedDialingLimitCount = 0
  1479. q.TCPPortForwardRejectedDisallowedCount = 0
  1480. q.UDPPortForwardRejectedDisallowedCount = 0
  1481. q.TCPIPv4PortForwardDialedCount = 0
  1482. q.TCPIPv4PortForwardDialedDuration = 0
  1483. q.TCPIPv4PortForwardFailedCount = 0
  1484. q.TCPIPv4PortForwardFailedDuration = 0
  1485. q.TCPIPv6PortForwardDialedCount = 0
  1486. q.TCPIPv6PortForwardDialedDuration = 0
  1487. q.TCPIPv6PortForwardFailedCount = 0
  1488. q.TCPIPv6PortForwardFailedDuration = 0
  1489. // Retain existing maps to avoid memory churn. The Go compiler optimizes map
  1490. // clearing operations of the following form.
  1491. for k := range q.DNSCount {
  1492. delete(q.DNSCount, k)
  1493. }
  1494. for k := range q.DNSDuration {
  1495. delete(q.DNSDuration, k)
  1496. }
  1497. for k := range q.DNSFailedCount {
  1498. delete(q.DNSFailedCount, k)
  1499. }
  1500. for k := range q.DNSFailedDuration {
  1501. delete(q.DNSFailedDuration, k)
  1502. }
  1503. }
  1504. type handshakeStateInfo struct {
  1505. activeAuthorizationIDs []string
  1506. authorizedAccessTypes []string
  1507. upstreamBytesPerSecond int64
  1508. downstreamBytesPerSecond int64
  1509. steeringIP string
  1510. }
  1511. type handshakeState struct {
  1512. completed bool
  1513. apiProtocol string
  1514. apiParams common.APIParameters
  1515. activeAuthorizationIDs []string
  1516. authorizedAccessTypes []string
  1517. authorizationsRevoked bool
  1518. domainBytesChecksum []byte
  1519. establishedTunnelsCount int
  1520. splitTunnelLookup *splitTunnelLookup
  1521. deviceRegion string
  1522. newTacticsTag string
  1523. inproxyClientIP string
  1524. inproxyClientGeoIPData GeoIPData
  1525. inproxyRelayLogFields common.LogFields
  1526. }
  1527. type destinationBytesMetrics struct {
  1528. bytesUp int64
  1529. bytesDown int64
  1530. }
  1531. func (d *destinationBytesMetrics) UpdateProgress(
  1532. downstreamBytes, upstreamBytes, _ int64) {
  1533. // Concurrency: UpdateProgress may be called without holding the sshClient
  1534. // lock; all accesses to bytesUp/bytesDown must use atomic operations.
  1535. atomic.AddInt64(&d.bytesUp, upstreamBytes)
  1536. atomic.AddInt64(&d.bytesDown, downstreamBytes)
  1537. }
  1538. func (d *destinationBytesMetrics) getBytesUp() int64 {
  1539. return atomic.LoadInt64(&d.bytesUp)
  1540. }
  1541. func (d *destinationBytesMetrics) getBytesDown() int64 {
  1542. return atomic.LoadInt64(&d.bytesDown)
  1543. }
  1544. type splitTunnelLookup struct {
  1545. regions []string
  1546. regionsLookup map[string]bool
  1547. }
  1548. func newSplitTunnelLookup(
  1549. ownRegion string,
  1550. otherRegions []string) (*splitTunnelLookup, error) {
  1551. length := len(otherRegions)
  1552. if ownRegion != "" {
  1553. length += 1
  1554. }
  1555. // This length check is a sanity check and prevents clients shipping
  1556. // excessively long lists which could impact performance.
  1557. if length > 250 {
  1558. return nil, errors.Tracef("too many regions: %d", length)
  1559. }
  1560. // Create map lookups for lists where the number of values to compare
  1561. // against exceeds a threshold where benchmarks show maps are faster than
  1562. // looping through a slice. Otherwise use a slice for lookups. In both
  1563. // cases, the input slice is no longer referenced.
  1564. if length >= stringLookupThreshold {
  1565. regionsLookup := make(map[string]bool)
  1566. if ownRegion != "" {
  1567. regionsLookup[ownRegion] = true
  1568. }
  1569. for _, region := range otherRegions {
  1570. regionsLookup[region] = true
  1571. }
  1572. return &splitTunnelLookup{
  1573. regionsLookup: regionsLookup,
  1574. }, nil
  1575. } else {
  1576. regions := []string{}
  1577. if ownRegion != "" && !common.Contains(otherRegions, ownRegion) {
  1578. regions = append(regions, ownRegion)
  1579. }
  1580. // TODO: check for other duplicate regions?
  1581. regions = append(regions, otherRegions...)
  1582. return &splitTunnelLookup{
  1583. regions: regions,
  1584. }, nil
  1585. }
  1586. }
  1587. func (lookup *splitTunnelLookup) lookup(region string) bool {
  1588. if lookup.regionsLookup != nil {
  1589. return lookup.regionsLookup[region]
  1590. } else {
  1591. return common.Contains(lookup.regions, region)
  1592. }
  1593. }
  1594. func newSshClient(
  1595. sshServer *sshServer,
  1596. sshListener *sshListener,
  1597. tunnelProtocol string,
  1598. transportData *additionalTransportData,
  1599. serverPacketManipulation string,
  1600. replayedServerPacketManipulation bool,
  1601. peerAddr net.Addr,
  1602. peerGeoIPData GeoIPData) *sshClient {
  1603. runCtx, stopRunning := context.WithCancel(context.Background())
  1604. // isFirstTunnelInSession is defaulted to true so that the pre-handshake
  1605. // traffic rules won't apply UnthrottleFirstTunnelOnly and negate any
  1606. // unthrottled bytes during the initial protocol negotiation.
  1607. client := &sshClient{
  1608. sshServer: sshServer,
  1609. sshListener: sshListener,
  1610. tunnelProtocol: tunnelProtocol,
  1611. isInproxyTunnelProtocol: protocol.TunnelProtocolUsesInproxy(tunnelProtocol),
  1612. additionalTransportData: transportData,
  1613. serverPacketManipulation: serverPacketManipulation,
  1614. replayedServerPacketManipulation: replayedServerPacketManipulation,
  1615. peerAddr: peerAddr,
  1616. isFirstTunnelInSession: true,
  1617. qualityMetrics: newQualityMetrics(),
  1618. tcpPortForwardLRU: common.NewLRUConns(),
  1619. signalIssueSLOKs: make(chan struct{}, 1),
  1620. runCtx: runCtx,
  1621. stopRunning: stopRunning,
  1622. stopped: make(chan struct{}),
  1623. sendAlertRequests: make(chan protocol.AlertRequest, ALERT_REQUEST_QUEUE_BUFFER_SIZE),
  1624. sentAlertRequests: make(map[string]bool),
  1625. }
  1626. client.tcpTrafficState.availablePortForwardCond = sync.NewCond(new(sync.Mutex))
  1627. client.udpTrafficState.availablePortForwardCond = sync.NewCond(new(sync.Mutex))
  1628. // In the case of in-proxy tunnel protocols, clientGeoIPData is not set
  1629. // until the original client IP is relayed from the broker during the
  1630. // handshake. In other cases, clientGeoIPData is the peerGeoIPData
  1631. // (this includes fronted meek).
  1632. client.peerGeoIPData = peerGeoIPData
  1633. if !client.isInproxyTunnelProtocol {
  1634. client.clientGeoIPData = peerGeoIPData
  1635. }
  1636. return client
  1637. }
  1638. // getClientGeoIPData gets sshClient.clientGeoIPData. Use this helper when
  1639. // accessing this field without already holding a lock on the sshClient
  1640. // mutex. Unlike older code and unlike with client.peerGeoIPData,
  1641. // sshClient.clientGeoIPData is not static and may get set during the
  1642. // handshake, and it is not safe to access it without a lock.
  1643. func (sshClient *sshClient) getClientGeoIPData() GeoIPData {
  1644. sshClient.Lock()
  1645. defer sshClient.Unlock()
  1646. return sshClient.clientGeoIPData
  1647. }
  1648. func (sshClient *sshClient) run(
  1649. baseConn net.Conn, onSSHHandshakeFinished func()) {
  1650. // When run returns, the client has fully stopped, with all SSH state torn
  1651. // down and no port forwards or API requests in progress.
  1652. defer close(sshClient.stopped)
  1653. // onSSHHandshakeFinished must be called even if the SSH handshake is aborted.
  1654. defer func() {
  1655. if onSSHHandshakeFinished != nil {
  1656. onSSHHandshakeFinished()
  1657. }
  1658. }()
  1659. // Set initial traffic rules, pre-handshake, based on currently known info.
  1660. sshClient.setTrafficRules()
  1661. conn := baseConn
  1662. // Wrap the base client connection with an ActivityMonitoredConn which will
  1663. // terminate the connection if no data is received before the deadline. This
  1664. // timeout is in effect for the entire duration of the SSH connection. Clients
  1665. // must actively use the connection or send SSH keep alive requests to keep
  1666. // the connection active. Writes are not considered reliable activity indicators
  1667. // due to buffering.
  1668. activityConn, err := common.NewActivityMonitoredConn(
  1669. conn,
  1670. SSH_CONNECTION_READ_DEADLINE,
  1671. false,
  1672. nil)
  1673. if err != nil {
  1674. conn.Close()
  1675. if !isExpectedTunnelIOError(err) {
  1676. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  1677. }
  1678. return
  1679. }
  1680. conn = activityConn
  1681. // Further wrap the connection with burst monitoring, when enabled.
  1682. //
  1683. // Limitations:
  1684. //
  1685. // - Burst parameters are fixed for the duration of the tunnel and do not
  1686. // change after a tactics hot reload.
  1687. //
  1688. // - In the case of in-proxy tunnel protocols, the original client IP is
  1689. // not yet known, and so burst monitoring GeoIP targeting uses the peer
  1690. // IP, which is the proxy, not the client.
  1691. var burstConn *common.BurstMonitoredConn
  1692. p, err := sshClient.sshServer.support.ServerTacticsParametersCache.Get(sshClient.peerGeoIPData)
  1693. if err != nil {
  1694. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Warning(
  1695. "ServerTacticsParametersCache.Get failed")
  1696. return
  1697. }
  1698. if !p.IsNil() {
  1699. upstreamTargetBytes := int64(p.Int(parameters.ServerBurstUpstreamTargetBytes))
  1700. upstreamDeadline := p.Duration(parameters.ServerBurstUpstreamDeadline)
  1701. downstreamTargetBytes := int64(p.Int(parameters.ServerBurstDownstreamTargetBytes))
  1702. downstreamDeadline := p.Duration(parameters.ServerBurstDownstreamDeadline)
  1703. if (upstreamDeadline != 0 && upstreamTargetBytes != 0) ||
  1704. (downstreamDeadline != 0 && downstreamTargetBytes != 0) {
  1705. burstConn = common.NewBurstMonitoredConn(
  1706. conn,
  1707. true,
  1708. upstreamTargetBytes, upstreamDeadline,
  1709. downstreamTargetBytes, downstreamDeadline)
  1710. conn = burstConn
  1711. }
  1712. }
  1713. // Allow garbage collection.
  1714. p.Close()
  1715. // Further wrap the connection in a rate limiting ThrottledConn.
  1716. throttledConn := common.NewThrottledConn(conn, sshClient.rateLimits())
  1717. conn = throttledConn
  1718. // Replay of server-side parameters is set or extended after a new tunnel
  1719. // meets duration and bytes transferred targets. Set a timer now that expires
  1720. // shortly after the target duration. When the timer fires, check the time of
  1721. // last byte read (a read indicating a live connection with the client),
  1722. // along with total bytes transferred and set or extend replay if the targets
  1723. // are met.
  1724. //
  1725. // Both target checks are conservative: the tunnel may be healthy, but a byte
  1726. // may not have been read in the last second when the timer fires. Or bytes
  1727. // may be transferring, but not at the target level. Only clients that meet
  1728. // the strict targets at the single check time will trigger replay; however,
  1729. // this replay will impact all clients with similar GeoIP data.
  1730. //
  1731. // A deferred function cancels the timer and also increments the replay
  1732. // failure counter, which will ultimately clear replay parameters, when the
  1733. // tunnel fails before the API handshake is completed (this includes any
  1734. // liveness test).
  1735. //
  1736. // A tunnel which fails to meet the targets but successfully completes any
  1737. // liveness test and the API handshake is ignored in terms of replay scoring.
  1738. //
  1739. // In the case of in-proxy tunnel protocols, the peer address will be the
  1740. // proxy, not the client, and GeoIP targeted replay will apply to the 2nd
  1741. // hop.
  1742. isReplayCandidate, replayWaitDuration, replayTargetDuration :=
  1743. sshClient.sshServer.support.ReplayCache.GetReplayTargetDuration(sshClient.peerGeoIPData)
  1744. if isReplayCandidate {
  1745. getFragmentorSeed := func() *prng.Seed {
  1746. fragmentor, ok := baseConn.(common.FragmentorAccessor)
  1747. if ok {
  1748. fragmentorSeed, _ := fragmentor.GetReplay()
  1749. return fragmentorSeed
  1750. }
  1751. return nil
  1752. }
  1753. setReplayAfterFunc := time.AfterFunc(
  1754. replayWaitDuration,
  1755. func() {
  1756. if activityConn.GetActiveDuration() >= replayTargetDuration {
  1757. sshClient.Lock()
  1758. bytesUp := sshClient.tcpTrafficState.bytesUp + sshClient.udpTrafficState.bytesUp
  1759. bytesDown := sshClient.tcpTrafficState.bytesDown + sshClient.udpTrafficState.bytesDown
  1760. sshClient.Unlock()
  1761. sshClient.sshServer.support.ReplayCache.SetReplayParameters(
  1762. sshClient.tunnelProtocol,
  1763. sshClient.peerGeoIPData,
  1764. sshClient.serverPacketManipulation,
  1765. getFragmentorSeed(),
  1766. bytesUp,
  1767. bytesDown)
  1768. }
  1769. })
  1770. defer func() {
  1771. setReplayAfterFunc.Stop()
  1772. completed, _ := sshClient.getHandshaked()
  1773. if !completed {
  1774. // Count a replay failure case when a tunnel used replay parameters
  1775. // (excluding OSSH fragmentation, which doesn't use the ReplayCache) and
  1776. // failed to complete the API handshake.
  1777. replayedFragmentation := false
  1778. if sshClient.tunnelProtocol != protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH {
  1779. fragmentor, ok := baseConn.(common.FragmentorAccessor)
  1780. if ok {
  1781. _, replayedFragmentation = fragmentor.GetReplay()
  1782. }
  1783. }
  1784. usedReplay := replayedFragmentation || sshClient.replayedServerPacketManipulation
  1785. if usedReplay {
  1786. sshClient.sshServer.support.ReplayCache.FailedReplayParameters(
  1787. sshClient.tunnelProtocol,
  1788. sshClient.peerGeoIPData,
  1789. sshClient.serverPacketManipulation,
  1790. getFragmentorSeed())
  1791. }
  1792. }
  1793. }()
  1794. }
  1795. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  1796. // respect shutdownBroadcast and implement a specific handshake timeout.
  1797. // The timeout is to reclaim network resources in case the handshake takes
  1798. // too long.
  1799. type sshNewServerConnResult struct {
  1800. obfuscatedSSHConn *obfuscator.ObfuscatedSSHConn
  1801. sshConn *ssh.ServerConn
  1802. channels <-chan ssh.NewChannel
  1803. requests <-chan *ssh.Request
  1804. err error
  1805. }
  1806. resultChannel := make(chan *sshNewServerConnResult, 2)
  1807. var sshHandshakeAfterFunc *time.Timer
  1808. if sshClient.sshServer.support.Config.sshHandshakeTimeout > 0 {
  1809. sshHandshakeAfterFunc = time.AfterFunc(sshClient.sshServer.support.Config.sshHandshakeTimeout, func() {
  1810. resultChannel <- &sshNewServerConnResult{err: std_errors.New("ssh handshake timeout")}
  1811. })
  1812. }
  1813. go func(baseConn, conn net.Conn) {
  1814. sshServerConfig := &ssh.ServerConfig{
  1815. PasswordCallback: sshClient.passwordCallback,
  1816. AuthLogCallback: sshClient.authLogCallback,
  1817. ServerVersion: sshClient.sshServer.support.Config.SSHServerVersion,
  1818. }
  1819. sshServerConfig.AddHostKey(sshClient.sshServer.sshHostKey)
  1820. var err error
  1821. if protocol.TunnelProtocolUsesObfuscatedSSH(sshClient.tunnelProtocol) {
  1822. // With Encrypt-then-MAC hash algorithms, packet length is
  1823. // transmitted in plaintext, which aids in traffic analysis;
  1824. // clients may still send Encrypt-then-MAC algorithms in their
  1825. // KEX_INIT message, but do not select these algorithms.
  1826. //
  1827. // The exception is TUNNEL_PROTOCOL_SSH, which is intended to appear
  1828. // like SSH on the wire.
  1829. sshServerConfig.NoEncryptThenMACHash = true
  1830. } else {
  1831. // For TUNNEL_PROTOCOL_SSH only, randomize KEX.
  1832. if sshClient.sshServer.support.Config.ObfuscatedSSHKey != "" {
  1833. sshServerConfig.KEXPRNGSeed, err = protocol.DeriveSSHServerKEXPRNGSeed(
  1834. sshClient.sshServer.support.Config.ObfuscatedSSHKey)
  1835. if err != nil {
  1836. err = errors.Trace(err)
  1837. }
  1838. }
  1839. }
  1840. result := &sshNewServerConnResult{}
  1841. // Wrap the connection in an SSH deobfuscator when required.
  1842. if err == nil && protocol.TunnelProtocolUsesObfuscatedSSH(sshClient.tunnelProtocol) {
  1843. // In the case of in-proxy tunnel protocols, the peer address will
  1844. // be the proxy, not the client, and GeoIP targeted server-side
  1845. // OSSH tactics, including prefixes, will apply to the 2nd hop.
  1846. //
  1847. // It is recommended to set ServerOSSHPrefixSpecs, etc., in default
  1848. // tactics.
  1849. p, err := sshClient.sshServer.support.ServerTacticsParametersCache.Get(sshClient.peerGeoIPData)
  1850. // Log error, but continue. A default prefix spec will be used by the server.
  1851. if err != nil {
  1852. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Warning(
  1853. "ServerTacticsParametersCache.Get failed")
  1854. }
  1855. var osshPrefixEnableFragmentor bool = false
  1856. var serverOsshPrefixSpecs transforms.Specs = nil
  1857. var minDelay, maxDelay time.Duration
  1858. if !p.IsNil() {
  1859. osshPrefixEnableFragmentor = p.Bool(parameters.OSSHPrefixEnableFragmentor)
  1860. serverOsshPrefixSpecs = p.ProtocolTransformSpecs(parameters.ServerOSSHPrefixSpecs)
  1861. minDelay = p.Duration(parameters.OSSHPrefixSplitMinDelay)
  1862. maxDelay = p.Duration(parameters.OSSHPrefixSplitMaxDelay)
  1863. // Allow garbage collection.
  1864. p.Close()
  1865. }
  1866. // Note: NewServerObfuscatedSSHConn blocks on network I/O
  1867. // TODO: ensure this won't block shutdown
  1868. result.obfuscatedSSHConn, err = obfuscator.NewServerObfuscatedSSHConn(
  1869. conn,
  1870. sshClient.sshServer.support.Config.ObfuscatedSSHKey,
  1871. sshClient.sshServer.obfuscatorSeedHistory,
  1872. serverOsshPrefixSpecs,
  1873. func(peerIP string, err error, logFields common.LogFields) {
  1874. logIrregularTunnel(
  1875. sshClient.sshServer.support,
  1876. sshClient.sshListener.tunnelProtocol,
  1877. sshClient.sshListener.port,
  1878. peerIP,
  1879. errors.Trace(err),
  1880. LogFields(logFields))
  1881. })
  1882. if err != nil {
  1883. err = errors.Trace(err)
  1884. } else {
  1885. conn = result.obfuscatedSSHConn
  1886. }
  1887. // Set the OSSH prefix split config.
  1888. if err == nil && result.obfuscatedSSHConn.IsOSSHPrefixStream() {
  1889. err = result.obfuscatedSSHConn.SetOSSHPrefixSplitConfig(minDelay, maxDelay)
  1890. // Log error, but continue.
  1891. if err != nil {
  1892. log.WithTraceFields(LogFields{"error": errors.Trace(err)}).Warning(
  1893. "SetOSSHPrefixSplitConfig failed")
  1894. }
  1895. }
  1896. // Seed the fragmentor, when present, with seed derived from initial
  1897. // obfuscator message. See tactics.Listener.Accept. This must preceed
  1898. // ssh.NewServerConn to ensure fragmentor is seeded before downstream bytes
  1899. // are written.
  1900. if err == nil && protocol.TunnelProtocolIsObfuscatedSSH(sshClient.tunnelProtocol) {
  1901. fragmentor, ok := baseConn.(common.FragmentorAccessor)
  1902. if ok {
  1903. var fragmentorPRNG *prng.PRNG
  1904. fragmentorPRNG, err = result.obfuscatedSSHConn.GetDerivedPRNG("server-side-fragmentor")
  1905. if err != nil {
  1906. err = errors.Trace(err)
  1907. } else {
  1908. fragmentor.SetReplay(fragmentorPRNG)
  1909. }
  1910. // Stops the fragmentor if disabled for prefixed OSSH streams.
  1911. if !osshPrefixEnableFragmentor && result.obfuscatedSSHConn.IsOSSHPrefixStream() {
  1912. fragmentor.StopFragmenting()
  1913. }
  1914. }
  1915. }
  1916. }
  1917. if err == nil {
  1918. result.sshConn, result.channels, result.requests, err =
  1919. ssh.NewServerConn(conn, sshServerConfig)
  1920. if err != nil {
  1921. err = errors.Trace(err)
  1922. }
  1923. }
  1924. result.err = err
  1925. resultChannel <- result
  1926. }(baseConn, conn)
  1927. var result *sshNewServerConnResult
  1928. select {
  1929. case result = <-resultChannel:
  1930. case <-sshClient.sshServer.shutdownBroadcast:
  1931. // Close() will interrupt an ongoing handshake
  1932. // TODO: wait for SSH handshake goroutines to exit before returning?
  1933. conn.Close()
  1934. return
  1935. }
  1936. if sshHandshakeAfterFunc != nil {
  1937. sshHandshakeAfterFunc.Stop()
  1938. }
  1939. if result.err != nil {
  1940. conn.Close()
  1941. // This is a Debug log due to noise. The handshake often fails due to I/O
  1942. // errors as clients frequently interrupt connections in progress when
  1943. // client-side load balancing completes a connection to a different server.
  1944. log.WithTraceFields(LogFields{"error": result.err}).Debug("SSH handshake failed")
  1945. return
  1946. }
  1947. // The SSH handshake has finished successfully; notify now to allow other
  1948. // blocked SSH handshakes to proceed.
  1949. if onSSHHandshakeFinished != nil {
  1950. onSSHHandshakeFinished()
  1951. }
  1952. onSSHHandshakeFinished = nil
  1953. sshClient.Lock()
  1954. sshClient.sshConn = result.sshConn
  1955. sshClient.throttledConn = throttledConn
  1956. sshClient.Unlock()
  1957. if !sshClient.sshServer.registerEstablishedClient(sshClient) {
  1958. conn.Close()
  1959. log.WithTrace().Warning("register failed")
  1960. return
  1961. }
  1962. sshClient.runTunnel(result.channels, result.requests)
  1963. // Note: sshServer.unregisterEstablishedClient calls sshClient.stop(),
  1964. // which also closes underlying transport Conn.
  1965. sshClient.sshServer.unregisterEstablishedClient(sshClient)
  1966. // Log tunnel metrics.
  1967. var additionalMetrics []LogFields
  1968. // Add activity and burst metrics.
  1969. //
  1970. // The reported duration is based on last confirmed data transfer, which for
  1971. // sshClient.activityConn.GetActiveDuration() is time of last read byte and
  1972. // not conn close time. This is important for protocols such as meek. For
  1973. // meek, the connection remains open until the HTTP session expires, which
  1974. // may be some time after the tunnel has closed. (The meek protocol has no
  1975. // allowance for signalling payload EOF, and even if it did the client may
  1976. // not have the opportunity to send a final request with an EOF flag set.)
  1977. activityMetrics := make(LogFields)
  1978. activityMetrics["start_time"] = activityConn.GetStartTime()
  1979. activityMetrics["duration"] = int64(activityConn.GetActiveDuration() / time.Millisecond)
  1980. additionalMetrics = append(additionalMetrics, activityMetrics)
  1981. if burstConn != nil {
  1982. // Any outstanding burst should be recorded by burstConn.Close which should
  1983. // be called by unregisterEstablishedClient.
  1984. additionalMetrics = append(
  1985. additionalMetrics, LogFields(burstConn.GetMetrics(activityConn.GetStartTime())))
  1986. }
  1987. // Some conns report additional metrics. Meek conns report resiliency
  1988. // metrics and fragmentor.Conns report fragmentor configs.
  1989. if metricsSource, ok := baseConn.(common.MetricsSource); ok {
  1990. additionalMetrics = append(
  1991. additionalMetrics, LogFields(metricsSource.GetMetrics()))
  1992. }
  1993. if result.obfuscatedSSHConn != nil {
  1994. additionalMetrics = append(
  1995. additionalMetrics, LogFields(result.obfuscatedSSHConn.GetMetrics()))
  1996. }
  1997. // Add server-replay metrics.
  1998. replayMetrics := make(LogFields)
  1999. replayedFragmentation := false
  2000. fragmentor, ok := baseConn.(common.FragmentorAccessor)
  2001. if ok {
  2002. _, replayedFragmentation = fragmentor.GetReplay()
  2003. }
  2004. replayMetrics["server_replay_fragmentation"] = replayedFragmentation
  2005. replayMetrics["server_replay_packet_manipulation"] = sshClient.replayedServerPacketManipulation
  2006. additionalMetrics = append(additionalMetrics, replayMetrics)
  2007. // Limitation: there's only one log per tunnel with bytes transferred
  2008. // metrics, so the byte count can't be attributed to a certain day for
  2009. // tunnels that remain connected for well over 24h. In practise, most
  2010. // tunnels are short-lived, especially on mobile devices.
  2011. sshClient.logTunnel(additionalMetrics)
  2012. // Transfer OSL seed state -- the OSL progress -- from the closing
  2013. // client to the session cache so the client can resume its progress
  2014. // if it reconnects to this same server.
  2015. // Note: following setOSLConfig order of locking.
  2016. sshClient.Lock()
  2017. if sshClient.oslClientSeedState != nil {
  2018. sshClient.sshServer.oslSessionCacheMutex.Lock()
  2019. sshClient.oslClientSeedState.Hibernate()
  2020. sshClient.sshServer.oslSessionCache.Set(
  2021. sshClient.sessionID, sshClient.oslClientSeedState, cache.DefaultExpiration)
  2022. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  2023. sshClient.oslClientSeedState = nil
  2024. }
  2025. sshClient.Unlock()
  2026. // Set the GeoIP session cache to expire; up to this point, the entry for
  2027. // this session ID has no expiry; retaining entries after the tunnel
  2028. // disconnects supports first-tunnel-in-session and duplicate
  2029. // authorization logic.
  2030. sshClient.sshServer.markGeoIPSessionCacheToExpire(sshClient.sessionID)
  2031. }
  2032. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  2033. expectedSessionIDLength := 2 * protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
  2034. expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH
  2035. var sshPasswordPayload protocol.SSHPasswordPayload
  2036. err := json.Unmarshal(password, &sshPasswordPayload)
  2037. if err != nil {
  2038. // Backwards compatibility case: instead of a JSON payload, older clients
  2039. // send the hex encoded session ID prepended to the SSH password.
  2040. // Note: there's an even older case where clients don't send any session ID,
  2041. // but that's no longer supported.
  2042. if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
  2043. sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
  2044. sshPasswordPayload.SshPassword = string(password[expectedSessionIDLength:])
  2045. } else {
  2046. return nil, errors.Tracef("invalid password payload for %q", conn.User())
  2047. }
  2048. }
  2049. if !isHexDigits(sshClient.sshServer.support.Config, sshPasswordPayload.SessionId) ||
  2050. len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
  2051. return nil, errors.Tracef("invalid session ID for %q", conn.User())
  2052. }
  2053. userOk := (subtle.ConstantTimeCompare(
  2054. []byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
  2055. passwordOk := (subtle.ConstantTimeCompare(
  2056. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
  2057. if !userOk || !passwordOk {
  2058. return nil, errors.Tracef("invalid password for %q", conn.User())
  2059. }
  2060. sessionID := sshPasswordPayload.SessionId
  2061. // The GeoIP session cache will be populated if there was a previous tunnel
  2062. // with this session ID. This will be true up to GEOIP_SESSION_CACHE_TTL.
  2063. isFirstTunnelInSession := !sshClient.sshServer.inGeoIPSessionCache(sessionID)
  2064. supportsServerRequests := common.Contains(
  2065. sshPasswordPayload.ClientCapabilities, protocol.CLIENT_CAPABILITY_SERVER_REQUESTS)
  2066. sshClient.Lock()
  2067. // After this point, these values are read-only as they are read
  2068. // without obtaining sshClient.Lock.
  2069. sshClient.sessionID = sessionID
  2070. sshClient.isFirstTunnelInSession = isFirstTunnelInSession
  2071. sshClient.supportsServerRequests = supportsServerRequests
  2072. sshClient.Unlock()
  2073. // Initially, in the case of in-proxy tunnel protocols, the GeoIP session
  2074. // cache entry will be the proxy's GeoIPData. This is updated to be the
  2075. // client's GeoIPData in setHandshakeState.
  2076. sshClient.sshServer.setGeoIPSessionCache(sessionID, sshClient.peerGeoIPData)
  2077. return nil, nil
  2078. }
  2079. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  2080. if err != nil {
  2081. if method == "none" && err.Error() == "ssh: no auth passed yet" {
  2082. // In this case, the callback invocation is noise from auth negotiation
  2083. return
  2084. }
  2085. // Note: here we previously logged messages for fail2ban to act on. This is no longer
  2086. // done as the complexity outweighs the benefits.
  2087. //
  2088. // - The SSH credential is not secret -- it's in the server entry. Attackers targeting
  2089. // the server likely already have the credential. On the other hand, random scanning and
  2090. // brute forcing is mitigated with high entropy random passwords, rate limiting
  2091. // (implemented on the host via iptables), and limited capabilities (the SSH session can
  2092. // only port forward).
  2093. //
  2094. // - fail2ban coverage was inconsistent; in the case of an unfronted meek protocol through
  2095. // an upstream proxy, the remote address is the upstream proxy, which should not be blocked.
  2096. // The X-Forwarded-For header cant be used instead as it may be forged and used to get IPs
  2097. // deliberately blocked; and in any case fail2ban adds iptables rules which can only block
  2098. // by direct remote IP, not by original client IP. Fronted meek has the same iptables issue.
  2099. //
  2100. // Random scanning and brute forcing of port 22 will result in log noise. To mitigate this,
  2101. // not every authentication failure is logged. A summary log is emitted periodically to
  2102. // retain some record of this activity in case this is relevant to, e.g., a performance
  2103. // investigation.
  2104. atomic.AddInt64(&sshClient.sshServer.authFailedCount, 1)
  2105. lastAuthLog := monotime.Time(atomic.LoadInt64(&sshClient.sshServer.lastAuthLog))
  2106. if monotime.Since(lastAuthLog) > SSH_AUTH_LOG_PERIOD {
  2107. now := int64(monotime.Now())
  2108. if atomic.CompareAndSwapInt64(&sshClient.sshServer.lastAuthLog, int64(lastAuthLog), now) {
  2109. count := atomic.SwapInt64(&sshClient.sshServer.authFailedCount, 0)
  2110. log.WithTraceFields(
  2111. LogFields{"lastError": err, "failedCount": count}).Warning("authentication failures")
  2112. }
  2113. }
  2114. log.WithTraceFields(LogFields{"error": err, "method": method}).Debug("authentication failed")
  2115. } else {
  2116. log.WithTraceFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  2117. }
  2118. }
  2119. // stop signals the ssh connection to shutdown. After sshConn.Wait returns,
  2120. // the SSH connection has terminated but sshClient.run may still be running and
  2121. // in the process of exiting.
  2122. //
  2123. // The shutdown process must complete rapidly and not, e.g., block on network
  2124. // I/O, as newly connecting clients need to await stop completion of any
  2125. // existing connection that shares the same session ID.
  2126. func (sshClient *sshClient) stop() {
  2127. sshClient.sshConn.Close()
  2128. sshClient.sshConn.Wait()
  2129. }
  2130. // awaitStopped will block until sshClient.run has exited, at which point all
  2131. // worker goroutines associated with the sshClient, including any in-flight
  2132. // API handlers, will have exited.
  2133. func (sshClient *sshClient) awaitStopped() {
  2134. <-sshClient.stopped
  2135. }
  2136. // runTunnel handles/dispatches new channels and new requests from the client.
  2137. // When the SSH client connection closes, both the channels and requests channels
  2138. // will close and runTunnel will exit.
  2139. func (sshClient *sshClient) runTunnel(
  2140. channels <-chan ssh.NewChannel,
  2141. requests <-chan *ssh.Request) {
  2142. waitGroup := new(sync.WaitGroup)
  2143. // Start client SSH API request handler
  2144. waitGroup.Add(1)
  2145. go func() {
  2146. defer waitGroup.Done()
  2147. sshClient.handleSSHRequests(requests)
  2148. }()
  2149. // Start request senders
  2150. if sshClient.supportsServerRequests {
  2151. waitGroup.Add(1)
  2152. go func() {
  2153. defer waitGroup.Done()
  2154. sshClient.runOSLSender()
  2155. }()
  2156. waitGroup.Add(1)
  2157. go func() {
  2158. defer waitGroup.Done()
  2159. sshClient.runAlertSender()
  2160. }()
  2161. }
  2162. // Start the TCP port forward manager
  2163. // The queue size is set to the traffic rules (MaxTCPPortForwardCount +
  2164. // MaxTCPDialingPortForwardCount), which is a reasonable indication of resource
  2165. // limits per client; when that value is not set, a default is used.
  2166. // A limitation: this queue size is set once and doesn't change, for this client,
  2167. // when traffic rules are reloaded.
  2168. queueSize := sshClient.getTCPPortForwardQueueSize()
  2169. if queueSize == 0 {
  2170. queueSize = SSH_TCP_PORT_FORWARD_QUEUE_SIZE
  2171. }
  2172. newTCPPortForwards := make(chan *newTCPPortForward, queueSize)
  2173. waitGroup.Add(1)
  2174. go func() {
  2175. defer waitGroup.Done()
  2176. sshClient.handleTCPPortForwards(waitGroup, newTCPPortForwards)
  2177. }()
  2178. // Handle new channel (port forward) requests from the client.
  2179. for newChannel := range channels {
  2180. switch newChannel.ChannelType() {
  2181. case protocol.RANDOM_STREAM_CHANNEL_TYPE:
  2182. sshClient.handleNewRandomStreamChannel(waitGroup, newChannel)
  2183. case protocol.PACKET_TUNNEL_CHANNEL_TYPE:
  2184. sshClient.handleNewPacketTunnelChannel(waitGroup, newChannel)
  2185. case protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE:
  2186. // The protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE is the same as
  2187. // "direct-tcpip", except split tunnel channel rejections are disallowed
  2188. // even if the client has enabled split tunnel. This channel type allows
  2189. // the client to ensure tunneling for certain cases while split tunnel is
  2190. // enabled.
  2191. sshClient.handleNewTCPPortForwardChannel(waitGroup, newChannel, false, newTCPPortForwards)
  2192. case "direct-tcpip":
  2193. sshClient.handleNewTCPPortForwardChannel(waitGroup, newChannel, true, newTCPPortForwards)
  2194. default:
  2195. sshClient.rejectNewChannel(newChannel,
  2196. fmt.Sprintf("unknown or unsupported channel type: %s", newChannel.ChannelType()))
  2197. }
  2198. }
  2199. // The channel loop is interrupted by a client
  2200. // disconnect or by calling sshClient.stop().
  2201. // Stop the TCP port forward manager
  2202. close(newTCPPortForwards)
  2203. // Stop all other worker goroutines
  2204. sshClient.stopRunning()
  2205. if sshClient.sshServer.support.Config.RunPacketTunnel {
  2206. // PacketTunnelServer.ClientDisconnected stops packet tunnel workers.
  2207. sshClient.sshServer.support.PacketTunnelServer.ClientDisconnected(
  2208. sshClient.sessionID)
  2209. }
  2210. waitGroup.Wait()
  2211. sshClient.cleanupAuthorizations()
  2212. }
  2213. func (sshClient *sshClient) handleSSHRequests(requests <-chan *ssh.Request) {
  2214. for request := range requests {
  2215. // Requests are processed serially; API responses must be sent in request order.
  2216. var responsePayload []byte
  2217. var err error
  2218. if request.Type == "keepalive@openssh.com" {
  2219. // SSH keep alive round trips are used as speed test samples.
  2220. responsePayload, err = tactics.MakeSpeedTestResponse(
  2221. SSH_KEEP_ALIVE_PAYLOAD_MIN_BYTES, SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES)
  2222. } else {
  2223. // All other requests are assumed to be API requests.
  2224. responsePayload, err = sshAPIRequestHandler(
  2225. sshClient.sshServer.support,
  2226. sshClient,
  2227. request.Type,
  2228. request.Payload)
  2229. }
  2230. if err == nil {
  2231. err = request.Reply(true, responsePayload)
  2232. } else {
  2233. log.WithTraceFields(LogFields{"error": err}).Warning("request failed")
  2234. err = request.Reply(false, nil)
  2235. }
  2236. if err != nil {
  2237. if !isExpectedTunnelIOError(err) {
  2238. log.WithTraceFields(LogFields{"error": err}).Warning("response failed")
  2239. }
  2240. }
  2241. }
  2242. }
  2243. type newTCPPortForward struct {
  2244. enqueueTime time.Time
  2245. hostToConnect string
  2246. portToConnect int
  2247. doSplitTunnel bool
  2248. newChannel ssh.NewChannel
  2249. }
  2250. func (sshClient *sshClient) handleTCPPortForwards(
  2251. waitGroup *sync.WaitGroup,
  2252. newTCPPortForwards chan *newTCPPortForward) {
  2253. // Lifecycle of a TCP port forward:
  2254. //
  2255. // 1. A "direct-tcpip" SSH request is received from the client.
  2256. //
  2257. // A new TCP port forward request is enqueued. The queue delivers TCP port
  2258. // forward requests to the TCP port forward manager, which enforces the TCP
  2259. // port forward dial limit.
  2260. //
  2261. // Enqueuing new requests allows for reading further SSH requests from the
  2262. // client without blocking when the dial limit is hit; this is to permit new
  2263. // UDP/udpgw port forwards to be restablished without delay. The maximum size
  2264. // of the queue enforces a hard cap on resources consumed by a client in the
  2265. // pre-dial phase. When the queue is full, new TCP port forwards are
  2266. // immediately rejected.
  2267. //
  2268. // 2. The TCP port forward manager dequeues the request.
  2269. //
  2270. // The manager calls dialingTCPPortForward(), which increments
  2271. // concurrentDialingPortForwardCount, and calls
  2272. // isTCPDialingPortForwardLimitExceeded() to check the concurrent dialing
  2273. // count.
  2274. //
  2275. // The manager enforces the concurrent TCP dial limit: when at the limit, the
  2276. // manager blocks waiting for the number of dials to drop below the limit before
  2277. // dispatching the request to handleTCPPortForward(), which will run in its own
  2278. // goroutine and will dial and relay the port forward.
  2279. //
  2280. // The block delays the current request and also halts dequeuing of subsequent
  2281. // requests and could ultimately cause requests to be immediately rejected if
  2282. // the queue fills. These actions are intended to apply back pressure when
  2283. // upstream network resources are impaired.
  2284. //
  2285. // The time spent in the queue is deducted from the port forward's dial timeout.
  2286. // The time spent blocking while at the dial limit is similarly deducted from
  2287. // the dial timeout. If the dial timeout has expired before the dial begins, the
  2288. // port forward is rejected and a stat is recorded.
  2289. //
  2290. // 3. handleTCPPortForward() performs the port forward dial and relaying.
  2291. //
  2292. // a. Dial the target, using the dial timeout remaining after queue and blocking
  2293. // time is deducted.
  2294. //
  2295. // b. If the dial fails, call abortedTCPPortForward() to decrement
  2296. // concurrentDialingPortForwardCount, freeing up a dial slot.
  2297. //
  2298. // c. If the dial succeeds, call establishedPortForward(), which decrements
  2299. // concurrentDialingPortForwardCount and increments concurrentPortForwardCount,
  2300. // the "established" port forward count.
  2301. //
  2302. // d. Check isPortForwardLimitExceeded(), which enforces the configurable limit on
  2303. // concurrentPortForwardCount, the number of _established_ TCP port forwards.
  2304. // If the limit is exceeded, the LRU established TCP port forward is closed and
  2305. // the newly established TCP port forward proceeds. This LRU logic allows some
  2306. // dangling resource consumption (e.g., TIME_WAIT) while providing a better
  2307. // experience for clients.
  2308. //
  2309. // e. Relay data.
  2310. //
  2311. // f. Call closedPortForward() which decrements concurrentPortForwardCount and
  2312. // records bytes transferred.
  2313. for newPortForward := range newTCPPortForwards {
  2314. remainingDialTimeout :=
  2315. time.Duration(sshClient.getDialTCPPortForwardTimeoutMilliseconds())*time.Millisecond -
  2316. time.Since(newPortForward.enqueueTime)
  2317. if remainingDialTimeout <= 0 {
  2318. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  2319. sshClient.rejectNewChannel(
  2320. newPortForward.newChannel, "TCP port forward timed out in queue")
  2321. continue
  2322. }
  2323. // Reserve a TCP dialing slot.
  2324. //
  2325. // TOCTOU note: important to increment counts _before_ checking limits; otherwise,
  2326. // the client could potentially consume excess resources by initiating many port
  2327. // forwards concurrently.
  2328. sshClient.dialingTCPPortForward()
  2329. // When max dials are in progress, wait up to remainingDialTimeout for dialing
  2330. // to become available. This blocks all dequeing.
  2331. if sshClient.isTCPDialingPortForwardLimitExceeded() {
  2332. blockStartTime := time.Now()
  2333. ctx, cancelCtx := context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  2334. sshClient.setTCPPortForwardDialingAvailableSignal(cancelCtx)
  2335. <-ctx.Done()
  2336. sshClient.setTCPPortForwardDialingAvailableSignal(nil)
  2337. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  2338. remainingDialTimeout -= time.Since(blockStartTime)
  2339. }
  2340. if remainingDialTimeout <= 0 {
  2341. // Release the dialing slot here since handleTCPChannel() won't be called.
  2342. sshClient.abortedTCPPortForward()
  2343. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  2344. sshClient.rejectNewChannel(
  2345. newPortForward.newChannel, "TCP port forward timed out before dialing")
  2346. continue
  2347. }
  2348. // Dial and relay the TCP port forward. handleTCPChannel is run in its own worker goroutine.
  2349. // handleTCPChannel will release the dialing slot reserved by dialingTCPPortForward(); and
  2350. // will deal with remainingDialTimeout <= 0.
  2351. waitGroup.Add(1)
  2352. go func(remainingDialTimeout time.Duration, newPortForward *newTCPPortForward) {
  2353. defer waitGroup.Done()
  2354. sshClient.handleTCPChannel(
  2355. remainingDialTimeout,
  2356. newPortForward.hostToConnect,
  2357. newPortForward.portToConnect,
  2358. newPortForward.doSplitTunnel,
  2359. newPortForward.newChannel)
  2360. }(remainingDialTimeout, newPortForward)
  2361. }
  2362. }
  2363. func (sshClient *sshClient) handleNewRandomStreamChannel(
  2364. waitGroup *sync.WaitGroup, newChannel ssh.NewChannel) {
  2365. // A random stream channel returns the requested number of bytes -- random
  2366. // bytes -- to the client while also consuming and discarding bytes sent
  2367. // by the client.
  2368. //
  2369. // One use case for the random stream channel is a liveness test that the
  2370. // client performs to confirm that the tunnel is live. As the liveness
  2371. // test is performed in the concurrent establishment phase, before
  2372. // selecting a single candidate for handshake, the random stream channel
  2373. // is available pre-handshake, albeit with additional restrictions.
  2374. //
  2375. // The random stream is subject to throttling in traffic rules; for
  2376. // unthrottled liveness tests, set EstablishmentRead/WriteBytesPerSecond as
  2377. // required. The random stream maximum count and response size cap mitigate
  2378. // clients abusing the facility to waste server resources.
  2379. //
  2380. // Like all other channels, this channel type is handled asynchronously,
  2381. // so it's possible to run at any point in the tunnel lifecycle.
  2382. //
  2383. // Up/downstream byte counts don't include SSH packet and request
  2384. // marshalling overhead.
  2385. var request protocol.RandomStreamRequest
  2386. err := json.Unmarshal(newChannel.ExtraData(), &request)
  2387. if err != nil {
  2388. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("invalid request: %s", err))
  2389. return
  2390. }
  2391. if request.UpstreamBytes > RANDOM_STREAM_MAX_BYTES {
  2392. sshClient.rejectNewChannel(newChannel,
  2393. fmt.Sprintf("invalid upstream bytes: %d", request.UpstreamBytes))
  2394. return
  2395. }
  2396. if request.DownstreamBytes > RANDOM_STREAM_MAX_BYTES {
  2397. sshClient.rejectNewChannel(newChannel,
  2398. fmt.Sprintf("invalid downstream bytes: %d", request.DownstreamBytes))
  2399. return
  2400. }
  2401. var metrics *randomStreamMetrics
  2402. sshClient.Lock()
  2403. if !sshClient.handshakeState.completed {
  2404. metrics = &sshClient.preHandshakeRandomStreamMetrics
  2405. } else {
  2406. metrics = &sshClient.postHandshakeRandomStreamMetrics
  2407. }
  2408. countOk := true
  2409. if !sshClient.handshakeState.completed &&
  2410. metrics.count >= PRE_HANDSHAKE_RANDOM_STREAM_MAX_COUNT {
  2411. countOk = false
  2412. } else {
  2413. metrics.count++
  2414. }
  2415. sshClient.Unlock()
  2416. if !countOk {
  2417. sshClient.rejectNewChannel(newChannel, "max count exceeded")
  2418. return
  2419. }
  2420. channel, requests, err := newChannel.Accept()
  2421. if err != nil {
  2422. if !isExpectedTunnelIOError(err) {
  2423. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  2424. }
  2425. return
  2426. }
  2427. go ssh.DiscardRequests(requests)
  2428. waitGroup.Add(1)
  2429. go func() {
  2430. defer waitGroup.Done()
  2431. upstream := new(sync.WaitGroup)
  2432. received := 0
  2433. sent := 0
  2434. if request.UpstreamBytes > 0 {
  2435. // Process streams concurrently to minimize elapsed time. This also
  2436. // avoids a unidirectional flow burst early in the tunnel lifecycle.
  2437. upstream.Add(1)
  2438. go func() {
  2439. defer upstream.Done()
  2440. n, err := io.CopyN(ioutil.Discard, channel, int64(request.UpstreamBytes))
  2441. received = int(n)
  2442. if err != nil {
  2443. if !isExpectedTunnelIOError(err) {
  2444. log.WithTraceFields(LogFields{"error": err}).Warning("receive failed")
  2445. }
  2446. }
  2447. }()
  2448. }
  2449. if request.DownstreamBytes > 0 {
  2450. n, err := io.CopyN(channel, rand.Reader, int64(request.DownstreamBytes))
  2451. sent = int(n)
  2452. if err != nil {
  2453. if !isExpectedTunnelIOError(err) {
  2454. log.WithTraceFields(LogFields{"error": err}).Warning("send failed")
  2455. }
  2456. }
  2457. }
  2458. upstream.Wait()
  2459. sshClient.Lock()
  2460. metrics.upstreamBytes += int64(request.UpstreamBytes)
  2461. metrics.receivedUpstreamBytes += int64(received)
  2462. metrics.downstreamBytes += int64(request.DownstreamBytes)
  2463. metrics.sentDownstreamBytes += int64(sent)
  2464. sshClient.Unlock()
  2465. channel.Close()
  2466. }()
  2467. }
  2468. func (sshClient *sshClient) handleNewPacketTunnelChannel(
  2469. waitGroup *sync.WaitGroup, newChannel ssh.NewChannel) {
  2470. // packet tunnel channels are handled by the packet tunnel server
  2471. // component. Each client may have at most one packet tunnel channel.
  2472. if !sshClient.sshServer.support.Config.RunPacketTunnel {
  2473. sshClient.rejectNewChannel(newChannel, "unsupported packet tunnel channel type")
  2474. return
  2475. }
  2476. // Accept this channel immediately. This channel will replace any
  2477. // previously existing packet tunnel channel for this client.
  2478. packetTunnelChannel, requests, err := newChannel.Accept()
  2479. if err != nil {
  2480. if !isExpectedTunnelIOError(err) {
  2481. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  2482. }
  2483. return
  2484. }
  2485. go ssh.DiscardRequests(requests)
  2486. sshClient.setPacketTunnelChannel(packetTunnelChannel)
  2487. // PacketTunnelServer will run the client's packet tunnel. If necessary, ClientConnected
  2488. // will stop packet tunnel workers for any previous packet tunnel channel.
  2489. checkAllowedTCPPortFunc := func(upstreamIPAddress net.IP, port int) bool {
  2490. return sshClient.isPortForwardPermitted(portForwardTypeTCP, upstreamIPAddress, port)
  2491. }
  2492. checkAllowedUDPPortFunc := func(upstreamIPAddress net.IP, port int) bool {
  2493. return sshClient.isPortForwardPermitted(portForwardTypeUDP, upstreamIPAddress, port)
  2494. }
  2495. checkAllowedDomainFunc := func(domain string) bool {
  2496. ok, _ := sshClient.isDomainPermitted(domain)
  2497. return ok
  2498. }
  2499. flowActivityUpdaterMaker := func(
  2500. isTCP bool, upstreamHostname string, upstreamIPAddress net.IP) []tun.FlowActivityUpdater {
  2501. trafficType := portForwardTypeTCP
  2502. if !isTCP {
  2503. trafficType = portForwardTypeUDP
  2504. }
  2505. activityUpdaters := sshClient.getActivityUpdaters(trafficType, upstreamIPAddress)
  2506. flowUpdaters := make([]tun.FlowActivityUpdater, len(activityUpdaters))
  2507. for i, activityUpdater := range activityUpdaters {
  2508. flowUpdaters[i] = activityUpdater
  2509. }
  2510. return flowUpdaters
  2511. }
  2512. metricUpdater := func(
  2513. TCPApplicationBytesDown, TCPApplicationBytesUp,
  2514. UDPApplicationBytesDown, UDPApplicationBytesUp int64) {
  2515. sshClient.Lock()
  2516. sshClient.tcpTrafficState.bytesDown += TCPApplicationBytesDown
  2517. sshClient.tcpTrafficState.bytesUp += TCPApplicationBytesUp
  2518. sshClient.udpTrafficState.bytesDown += UDPApplicationBytesDown
  2519. sshClient.udpTrafficState.bytesUp += UDPApplicationBytesUp
  2520. sshClient.Unlock()
  2521. }
  2522. dnsQualityReporter := sshClient.updateQualityMetricsWithDNSResult
  2523. err = sshClient.sshServer.support.PacketTunnelServer.ClientConnected(
  2524. sshClient.sessionID,
  2525. packetTunnelChannel,
  2526. checkAllowedTCPPortFunc,
  2527. checkAllowedUDPPortFunc,
  2528. checkAllowedDomainFunc,
  2529. flowActivityUpdaterMaker,
  2530. metricUpdater,
  2531. dnsQualityReporter)
  2532. if err != nil {
  2533. log.WithTraceFields(LogFields{"error": err}).Warning("start packet tunnel client failed")
  2534. sshClient.setPacketTunnelChannel(nil)
  2535. }
  2536. }
  2537. func (sshClient *sshClient) handleNewTCPPortForwardChannel(
  2538. waitGroup *sync.WaitGroup,
  2539. newChannel ssh.NewChannel,
  2540. allowSplitTunnel bool,
  2541. newTCPPortForwards chan *newTCPPortForward) {
  2542. // udpgw client connections are dispatched immediately (clients use this for
  2543. // DNS, so it's essential to not block; and only one udpgw connection is
  2544. // retained at a time).
  2545. //
  2546. // All other TCP port forwards are dispatched via the TCP port forward
  2547. // manager queue.
  2548. // http://tools.ietf.org/html/rfc4254#section-7.2
  2549. var directTcpipExtraData struct {
  2550. HostToConnect string
  2551. PortToConnect uint32
  2552. OriginatorIPAddress string
  2553. OriginatorPort uint32
  2554. }
  2555. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  2556. if err != nil {
  2557. sshClient.rejectNewChannel(newChannel, "invalid extra data")
  2558. return
  2559. }
  2560. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  2561. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  2562. isUdpgwChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
  2563. sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
  2564. net.JoinHostPort(directTcpipExtraData.HostToConnect, strconv.Itoa(int(directTcpipExtraData.PortToConnect)))
  2565. if isUdpgwChannel {
  2566. // Dispatch immediately. handleUDPChannel runs the udpgw protocol in its
  2567. // own worker goroutine.
  2568. waitGroup.Add(1)
  2569. go func(channel ssh.NewChannel) {
  2570. defer waitGroup.Done()
  2571. sshClient.handleUdpgwChannel(channel)
  2572. }(newChannel)
  2573. } else {
  2574. // Dispatch via TCP port forward manager. When the queue is full, the channel
  2575. // is immediately rejected.
  2576. //
  2577. // Split tunnel logic is enabled for this TCP port forward when the client
  2578. // has enabled split tunnel mode and the channel type allows it.
  2579. doSplitTunnel := sshClient.handshakeState.splitTunnelLookup != nil && allowSplitTunnel
  2580. tcpPortForward := &newTCPPortForward{
  2581. enqueueTime: time.Now(),
  2582. hostToConnect: directTcpipExtraData.HostToConnect,
  2583. portToConnect: int(directTcpipExtraData.PortToConnect),
  2584. doSplitTunnel: doSplitTunnel,
  2585. newChannel: newChannel,
  2586. }
  2587. select {
  2588. case newTCPPortForwards <- tcpPortForward:
  2589. default:
  2590. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  2591. sshClient.rejectNewChannel(newChannel, "TCP port forward dial queue full")
  2592. }
  2593. }
  2594. }
  2595. func (sshClient *sshClient) cleanupAuthorizations() {
  2596. sshClient.Lock()
  2597. if sshClient.releaseAuthorizations != nil {
  2598. sshClient.releaseAuthorizations()
  2599. }
  2600. if sshClient.stopTimer != nil {
  2601. sshClient.stopTimer.Stop()
  2602. }
  2603. sshClient.Unlock()
  2604. }
  2605. // setPacketTunnelChannel sets the single packet tunnel channel
  2606. // for this sshClient. Any existing packet tunnel channel is
  2607. // closed.
  2608. func (sshClient *sshClient) setPacketTunnelChannel(channel ssh.Channel) {
  2609. sshClient.Lock()
  2610. if sshClient.packetTunnelChannel != nil {
  2611. sshClient.packetTunnelChannel.Close()
  2612. }
  2613. sshClient.packetTunnelChannel = channel
  2614. sshClient.totalPacketTunnelChannelCount += 1
  2615. sshClient.Unlock()
  2616. }
  2617. // setUdpgwChannelHandler sets the single udpgw channel handler for this
  2618. // sshClient. Each sshClient may have only one concurrent udpgw
  2619. // channel/handler. Each udpgw channel multiplexes many UDP port forwards via
  2620. // the udpgw protocol. Any existing udpgw channel/handler is closed.
  2621. func (sshClient *sshClient) setUdpgwChannelHandler(udpgwChannelHandler *udpgwPortForwardMultiplexer) bool {
  2622. sshClient.Lock()
  2623. if sshClient.udpgwChannelHandler != nil {
  2624. previousHandler := sshClient.udpgwChannelHandler
  2625. sshClient.udpgwChannelHandler = nil
  2626. // stop must be run without holding the sshClient mutex lock, as the
  2627. // udpgw goroutines may attempt to lock the same mutex. For example,
  2628. // udpgwPortForwardMultiplexer.run calls sshClient.establishedPortForward
  2629. // which calls sshClient.allocatePortForward.
  2630. sshClient.Unlock()
  2631. previousHandler.stop()
  2632. sshClient.Lock()
  2633. // In case some other channel has set the sshClient.udpgwChannelHandler
  2634. // in the meantime, fail. The caller should discard this channel/handler.
  2635. if sshClient.udpgwChannelHandler != nil {
  2636. sshClient.Unlock()
  2637. return false
  2638. }
  2639. }
  2640. sshClient.udpgwChannelHandler = udpgwChannelHandler
  2641. sshClient.totalUdpgwChannelCount += 1
  2642. sshClient.Unlock()
  2643. return true
  2644. }
  2645. var serverTunnelStatParams = append(
  2646. []requestParamSpec{
  2647. {"last_connected", isLastConnected, requestParamOptional},
  2648. {"establishment_duration", isIntString, requestParamOptional}},
  2649. baseSessionAndDialParams...)
  2650. func (sshClient *sshClient) logTunnel(additionalMetrics []LogFields) {
  2651. sshClient.Lock()
  2652. // For in-proxy tunnel protocols, two sets of GeoIP fields are logged, one
  2653. // for the client and one for the proxy. The client GeoIP fields will
  2654. // be "None" if handshake did not complete.
  2655. logFields := getRequestLogFields(
  2656. "server_tunnel",
  2657. sshClient.clientGeoIPData,
  2658. sshClient.handshakeState.authorizedAccessTypes,
  2659. sshClient.handshakeState.apiParams,
  2660. serverTunnelStatParams)
  2661. if sshClient.isInproxyTunnelProtocol {
  2662. sshClient.peerGeoIPData.SetLogFieldsWithPrefix("", "proxy", logFields)
  2663. logFields.Add(
  2664. LogFields(sshClient.handshakeState.inproxyRelayLogFields))
  2665. }
  2666. // new_tactics_tag indicates that the handshake returned new tactics.
  2667. if sshClient.handshakeState.newTacticsTag != "" {
  2668. logFields["new_tactics_tag"] = sshClient.handshakeState.newTacticsTag
  2669. }
  2670. // "relay_protocol" is sent with handshake API parameters. In pre-
  2671. // handshake logTunnel cases, this value is not yet known. As
  2672. // sshClient.tunnelProtocol is authoritative, set this value
  2673. // unconditionally, overwriting any value from handshake.
  2674. logFields["relay_protocol"] = sshClient.tunnelProtocol
  2675. if sshClient.serverPacketManipulation != "" {
  2676. logFields["server_packet_manipulation"] = sshClient.serverPacketManipulation
  2677. }
  2678. if sshClient.sshListener.BPFProgramName != "" {
  2679. logFields["server_bpf"] = sshClient.sshListener.BPFProgramName
  2680. }
  2681. logFields["session_id"] = sshClient.sessionID
  2682. logFields["is_first_tunnel_in_session"] = sshClient.isFirstTunnelInSession
  2683. logFields["handshake_completed"] = sshClient.handshakeState.completed
  2684. logFields["bytes_up_tcp"] = sshClient.tcpTrafficState.bytesUp
  2685. logFields["bytes_down_tcp"] = sshClient.tcpTrafficState.bytesDown
  2686. logFields["peak_concurrent_dialing_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentDialingPortForwardCount
  2687. logFields["peak_concurrent_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentPortForwardCount
  2688. logFields["total_port_forward_count_tcp"] = sshClient.tcpTrafficState.totalPortForwardCount
  2689. logFields["bytes_up_udp"] = sshClient.udpTrafficState.bytesUp
  2690. logFields["bytes_down_udp"] = sshClient.udpTrafficState.bytesDown
  2691. // sshClient.udpTrafficState.peakConcurrentDialingPortForwardCount isn't meaningful
  2692. logFields["peak_concurrent_port_forward_count_udp"] = sshClient.udpTrafficState.peakConcurrentPortForwardCount
  2693. logFields["total_port_forward_count_udp"] = sshClient.udpTrafficState.totalPortForwardCount
  2694. logFields["total_udpgw_channel_count"] = sshClient.totalUdpgwChannelCount
  2695. logFields["total_packet_tunnel_channel_count"] = sshClient.totalPacketTunnelChannelCount
  2696. logFields["pre_handshake_random_stream_count"] = sshClient.preHandshakeRandomStreamMetrics.count
  2697. logFields["pre_handshake_random_stream_upstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.upstreamBytes
  2698. logFields["pre_handshake_random_stream_received_upstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.receivedUpstreamBytes
  2699. logFields["pre_handshake_random_stream_downstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.downstreamBytes
  2700. logFields["pre_handshake_random_stream_sent_downstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.sentDownstreamBytes
  2701. logFields["random_stream_count"] = sshClient.postHandshakeRandomStreamMetrics.count
  2702. logFields["random_stream_upstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.upstreamBytes
  2703. logFields["random_stream_received_upstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.receivedUpstreamBytes
  2704. logFields["random_stream_downstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.downstreamBytes
  2705. logFields["random_stream_sent_downstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.sentDownstreamBytes
  2706. if sshClient.destinationBytesMetricsASN != "" {
  2707. // Check if the configured DestinationBytesMetricsASN has changed
  2708. // (or been cleared). If so, don't log and discard the accumulated
  2709. // bytes to ensure we don't continue to record stats as previously
  2710. // configured.
  2711. //
  2712. // Any counts accumulated before the DestinationBytesMetricsASN change
  2713. // are lost. At this time we can't change
  2714. // sshClient.destinationBytesMetricsASN dynamically, after a tactics
  2715. // hot reload, as there may be destination bytes port forwards that
  2716. // were in place before the change, which will continue to count.
  2717. logDestBytes := true
  2718. if sshClient.sshServer.support.ServerTacticsParametersCache != nil {
  2719. // Target this using the client, not peer, GeoIP. In the case of
  2720. // in-proxy tunnel protocols, the client GeoIP fields will be None
  2721. // if the handshake does not complete. In that case, no bytes will
  2722. // have transferred.
  2723. p, err := sshClient.sshServer.support.ServerTacticsParametersCache.Get(sshClient.clientGeoIPData)
  2724. if err != nil || p.IsNil() ||
  2725. sshClient.destinationBytesMetricsASN != p.String(parameters.DestinationBytesMetricsASN) {
  2726. logDestBytes = false
  2727. }
  2728. }
  2729. if logDestBytes {
  2730. bytesUpTCP := sshClient.tcpDestinationBytesMetrics.getBytesUp()
  2731. bytesDownTCP := sshClient.tcpDestinationBytesMetrics.getBytesDown()
  2732. bytesUpUDP := sshClient.udpDestinationBytesMetrics.getBytesUp()
  2733. bytesDownUDP := sshClient.udpDestinationBytesMetrics.getBytesDown()
  2734. logFields["dest_bytes_asn"] = sshClient.destinationBytesMetricsASN
  2735. logFields["dest_bytes_up_tcp"] = bytesUpTCP
  2736. logFields["dest_bytes_down_tcp"] = bytesDownTCP
  2737. logFields["dest_bytes_up_udp"] = bytesUpUDP
  2738. logFields["dest_bytes_down_udp"] = bytesDownUDP
  2739. logFields["dest_bytes"] = bytesUpTCP + bytesDownTCP + bytesUpUDP + bytesDownUDP
  2740. }
  2741. }
  2742. // Only log fields for peakMetrics when there is data recorded, otherwise
  2743. // omit the field.
  2744. if sshClient.peakMetrics.concurrentProximateAcceptedClients != nil {
  2745. logFields["peak_concurrent_proximate_accepted_clients"] = *sshClient.peakMetrics.concurrentProximateAcceptedClients
  2746. }
  2747. if sshClient.peakMetrics.concurrentProximateEstablishedClients != nil {
  2748. logFields["peak_concurrent_proximate_established_clients"] = *sshClient.peakMetrics.concurrentProximateEstablishedClients
  2749. }
  2750. if sshClient.peakMetrics.TCPPortForwardFailureRate != nil && sshClient.peakMetrics.TCPPortForwardFailureRateSampleSize != nil {
  2751. logFields["peak_tcp_port_forward_failure_rate"] = *sshClient.peakMetrics.TCPPortForwardFailureRate
  2752. logFields["peak_tcp_port_forward_failure_rate_sample_size"] = *sshClient.peakMetrics.TCPPortForwardFailureRateSampleSize
  2753. }
  2754. if sshClient.peakMetrics.DNSFailureRate != nil && sshClient.peakMetrics.DNSFailureRateSampleSize != nil {
  2755. logFields["peak_dns_failure_rate"] = *sshClient.peakMetrics.DNSFailureRate
  2756. logFields["peak_dns_failure_rate_sample_size"] = *sshClient.peakMetrics.DNSFailureRateSampleSize
  2757. }
  2758. // Pre-calculate a total-tunneled-bytes field. This total is used
  2759. // extensively in analytics and is more performant when pre-calculated.
  2760. logFields["bytes"] = sshClient.tcpTrafficState.bytesUp +
  2761. sshClient.tcpTrafficState.bytesDown +
  2762. sshClient.udpTrafficState.bytesUp +
  2763. sshClient.udpTrafficState.bytesDown
  2764. // Merge in additional metrics from the optional metrics source
  2765. for _, metrics := range additionalMetrics {
  2766. for name, value := range metrics {
  2767. // Don't overwrite any basic fields
  2768. if logFields[name] == nil {
  2769. logFields[name] = value
  2770. }
  2771. }
  2772. }
  2773. if sshClient.additionalTransportData != nil &&
  2774. sshClient.additionalTransportData.steeringIP != "" {
  2775. logFields["relayed_steering_ip"] = sshClient.additionalTransportData.steeringIP
  2776. }
  2777. // Retain lock when invoking LogRawFieldsWithTimestamp to block any
  2778. // concurrent writes to variables referenced by logFields.
  2779. log.LogRawFieldsWithTimestamp(logFields)
  2780. sshClient.Unlock()
  2781. }
  2782. var blocklistHitsStatParams = []requestParamSpec{
  2783. {"propagation_channel_id", isHexDigits, 0},
  2784. {"sponsor_id", isHexDigits, 0},
  2785. {"client_version", isIntString, requestParamLogStringAsInt},
  2786. {"client_platform", isClientPlatform, 0},
  2787. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  2788. {"client_build_rev", isHexDigits, requestParamOptional},
  2789. {"device_region", isAnyString, requestParamOptional},
  2790. {"device_location", isGeoHashString, requestParamOptional},
  2791. {"egress_region", isRegionCode, requestParamOptional},
  2792. {"session_id", isHexDigits, 0},
  2793. {"last_connected", isLastConnected, requestParamOptional},
  2794. }
  2795. func (sshClient *sshClient) logBlocklistHits(IP net.IP, domain string, tags []BlocklistTag) {
  2796. sshClient.Lock()
  2797. // Log this using the client, not peer, GeoIP. In the case of in-proxy
  2798. // tunnel protocols, the client GeoIP fields will be None if the
  2799. // handshake does not complete. In that case, no port forwarding will
  2800. // occur and there will not be any blocklist hits.
  2801. logFields := getRequestLogFields(
  2802. "server_blocklist_hit",
  2803. sshClient.clientGeoIPData,
  2804. sshClient.handshakeState.authorizedAccessTypes,
  2805. sshClient.handshakeState.apiParams,
  2806. blocklistHitsStatParams)
  2807. logFields["session_id"] = sshClient.sessionID
  2808. // Note: see comment in logTunnel regarding unlock and concurrent access.
  2809. sshClient.Unlock()
  2810. for _, tag := range tags {
  2811. if IP != nil {
  2812. logFields["blocklist_ip_address"] = IP.String()
  2813. }
  2814. if domain != "" {
  2815. logFields["blocklist_domain"] = domain
  2816. }
  2817. logFields["blocklist_source"] = tag.Source
  2818. logFields["blocklist_subject"] = tag.Subject
  2819. log.LogRawFieldsWithTimestamp(logFields)
  2820. }
  2821. }
  2822. func (sshClient *sshClient) runOSLSender() {
  2823. for {
  2824. // Await a signal that there are SLOKs to send
  2825. // TODO: use reflect.SelectCase, and optionally await timer here?
  2826. select {
  2827. case <-sshClient.signalIssueSLOKs:
  2828. case <-sshClient.runCtx.Done():
  2829. return
  2830. }
  2831. retryDelay := SSH_SEND_OSL_INITIAL_RETRY_DELAY
  2832. for {
  2833. err := sshClient.sendOSLRequest()
  2834. if err == nil {
  2835. break
  2836. }
  2837. if !isExpectedTunnelIOError(err) {
  2838. log.WithTraceFields(LogFields{"error": err}).Warning("sendOSLRequest failed")
  2839. }
  2840. // If the request failed, retry after a delay (with exponential backoff)
  2841. // or when signaled that there are additional SLOKs to send
  2842. retryTimer := time.NewTimer(retryDelay)
  2843. select {
  2844. case <-retryTimer.C:
  2845. case <-sshClient.signalIssueSLOKs:
  2846. case <-sshClient.runCtx.Done():
  2847. retryTimer.Stop()
  2848. return
  2849. }
  2850. retryTimer.Stop()
  2851. retryDelay *= SSH_SEND_OSL_RETRY_FACTOR
  2852. }
  2853. }
  2854. }
  2855. // sendOSLRequest will invoke osl.GetSeedPayload to issue SLOKs and
  2856. // generate a payload, and send an OSL request to the client when
  2857. // there are new SLOKs in the payload.
  2858. func (sshClient *sshClient) sendOSLRequest() error {
  2859. seedPayload := sshClient.getOSLSeedPayload()
  2860. // Don't send when no SLOKs. This will happen when signalIssueSLOKs
  2861. // is received but no new SLOKs are issued.
  2862. if len(seedPayload.SLOKs) == 0 {
  2863. return nil
  2864. }
  2865. oslRequest := protocol.OSLRequest{
  2866. SeedPayload: seedPayload,
  2867. }
  2868. requestPayload, err := json.Marshal(oslRequest)
  2869. if err != nil {
  2870. return errors.Trace(err)
  2871. }
  2872. ok, _, err := sshClient.sshConn.SendRequest(
  2873. protocol.PSIPHON_API_OSL_REQUEST_NAME,
  2874. true,
  2875. requestPayload)
  2876. if err != nil {
  2877. return errors.Trace(err)
  2878. }
  2879. if !ok {
  2880. return errors.TraceNew("client rejected request")
  2881. }
  2882. sshClient.clearOSLSeedPayload()
  2883. return nil
  2884. }
  2885. // runAlertSender dequeues and sends alert requests to the client. As these
  2886. // alerts are informational, there is no retry logic and no SSH client
  2887. // acknowledgement (wantReply) is requested. This worker scheme allows
  2888. // nonconcurrent components including udpgw and packet tunnel to enqueue
  2889. // alerts without blocking their traffic processing.
  2890. func (sshClient *sshClient) runAlertSender() {
  2891. for {
  2892. select {
  2893. case <-sshClient.runCtx.Done():
  2894. return
  2895. case request := <-sshClient.sendAlertRequests:
  2896. payload, err := json.Marshal(request)
  2897. if err != nil {
  2898. log.WithTraceFields(LogFields{"error": err}).Warning("Marshal failed")
  2899. break
  2900. }
  2901. _, _, err = sshClient.sshConn.SendRequest(
  2902. protocol.PSIPHON_API_ALERT_REQUEST_NAME,
  2903. false,
  2904. payload)
  2905. if err != nil && !isExpectedTunnelIOError(err) {
  2906. log.WithTraceFields(LogFields{"error": err}).Warning("SendRequest failed")
  2907. break
  2908. }
  2909. sshClient.Lock()
  2910. sshClient.sentAlertRequests[fmt.Sprintf("%+v", request)] = true
  2911. sshClient.Unlock()
  2912. }
  2913. }
  2914. }
  2915. // enqueueAlertRequest enqueues an alert request to be sent to the client.
  2916. // Only one request is sent per tunnel per protocol.AlertRequest value;
  2917. // subsequent alerts with the same value are dropped. enqueueAlertRequest will
  2918. // not block until the queue exceeds ALERT_REQUEST_QUEUE_BUFFER_SIZE.
  2919. func (sshClient *sshClient) enqueueAlertRequest(request protocol.AlertRequest) {
  2920. sshClient.Lock()
  2921. if sshClient.sentAlertRequests[fmt.Sprintf("%+v", request)] {
  2922. sshClient.Unlock()
  2923. return
  2924. }
  2925. sshClient.Unlock()
  2926. select {
  2927. case <-sshClient.runCtx.Done():
  2928. case sshClient.sendAlertRequests <- request:
  2929. }
  2930. }
  2931. func (sshClient *sshClient) enqueueDisallowedTrafficAlertRequest() {
  2932. reason := protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC
  2933. actionURLs := sshClient.getAlertActionURLs(reason)
  2934. sshClient.enqueueAlertRequest(
  2935. protocol.AlertRequest{
  2936. Reason: reason,
  2937. ActionURLs: actionURLs,
  2938. })
  2939. }
  2940. func (sshClient *sshClient) enqueueUnsafeTrafficAlertRequest(tags []BlocklistTag) {
  2941. reason := protocol.PSIPHON_API_ALERT_UNSAFE_TRAFFIC
  2942. actionURLs := sshClient.getAlertActionURLs(reason)
  2943. for _, tag := range tags {
  2944. sshClient.enqueueAlertRequest(
  2945. protocol.AlertRequest{
  2946. Reason: reason,
  2947. Subject: tag.Subject,
  2948. ActionURLs: actionURLs,
  2949. })
  2950. }
  2951. }
  2952. func (sshClient *sshClient) getAlertActionURLs(alertReason string) []string {
  2953. sshClient.Lock()
  2954. sponsorID, _ := getStringRequestParam(
  2955. sshClient.handshakeState.apiParams, "sponsor_id")
  2956. clientGeoIPData := sshClient.clientGeoIPData
  2957. deviceRegion := sshClient.handshakeState.deviceRegion
  2958. sshClient.Unlock()
  2959. return sshClient.sshServer.support.PsinetDatabase.GetAlertActionURLs(
  2960. alertReason,
  2961. sponsorID,
  2962. clientGeoIPData.Country,
  2963. clientGeoIPData.ASN,
  2964. deviceRegion)
  2965. }
  2966. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, logMessage string) {
  2967. // We always return the reject reason "Prohibited":
  2968. // - Traffic rules and connection limits may prohibit the connection.
  2969. // - External firewall rules may prohibit the connection, and this is not currently
  2970. // distinguishable from other failure modes.
  2971. // - We limit the failure information revealed to the client.
  2972. reason := ssh.Prohibited
  2973. // Note: Debug level, as logMessage may contain user traffic destination address information
  2974. log.WithTraceFields(
  2975. LogFields{
  2976. "channelType": newChannel.ChannelType(),
  2977. "logMessage": logMessage,
  2978. "rejectReason": reason.String(),
  2979. }).Debug("reject new channel")
  2980. // Note: logMessage is internal, for logging only; just the reject reason is sent to the client.
  2981. newChannel.Reject(reason, reason.String())
  2982. }
  2983. // setHandshakeState sets the handshake state -- that it completed and
  2984. // what parameters were passed -- in sshClient. This state is used for allowing
  2985. // port forwards and for future traffic rule selection. setHandshakeState
  2986. // also triggers an immediate traffic rule re-selection, as the rules selected
  2987. // upon tunnel establishment may no longer apply now that handshake values are
  2988. // set.
  2989. //
  2990. // The authorizations received from the client handshake are verified and the
  2991. // resulting list of authorized access types are applied to the client's tunnel
  2992. // and traffic rules.
  2993. //
  2994. // A list of active authorization IDs, authorized access types, and traffic
  2995. // rate limits are returned for responding to the client and logging.
  2996. //
  2997. // All slices in the returnd handshakeStateInfo are read-only, as readers may
  2998. // reference slice contents outside of locks.
  2999. func (sshClient *sshClient) setHandshakeState(
  3000. state handshakeState,
  3001. authorizations []string) (*handshakeStateInfo, error) {
  3002. sshClient.Lock()
  3003. completed := sshClient.handshakeState.completed
  3004. if !completed {
  3005. sshClient.handshakeState = state
  3006. if sshClient.isInproxyTunnelProtocol {
  3007. // Set the client GeoIP data to the value obtained using the
  3008. // original client IP, from the broker, in the handshake. Also
  3009. // update the GeoIP session hash to use the client GeoIP data.
  3010. sshClient.clientGeoIPData =
  3011. sshClient.handshakeState.inproxyClientGeoIPData
  3012. sshClient.sshServer.setGeoIPSessionCache(
  3013. sshClient.sessionID, sshClient.clientGeoIPData)
  3014. }
  3015. }
  3016. sshClient.Unlock()
  3017. // Client must only perform one handshake
  3018. if completed {
  3019. return nil, errors.TraceNew("handshake already completed")
  3020. }
  3021. // Verify the authorizations submitted by the client. Verified, active
  3022. // (non-expired) access types will be available for traffic rules
  3023. // filtering.
  3024. //
  3025. // When an authorization is active but expires while the client is
  3026. // connected, the client is disconnected to ensure the access is reset.
  3027. // This is implemented by setting a timer to perform the disconnect at the
  3028. // expiry time of the soonest expiring authorization.
  3029. //
  3030. // sshServer.authorizationSessionIDs tracks the unique mapping of active
  3031. // authorization IDs to client session IDs and is used to detect and
  3032. // prevent multiple malicious clients from reusing a single authorization
  3033. // (within the scope of this server).
  3034. // authorizationIDs and authorizedAccessTypes are returned to the client
  3035. // and logged, respectively; initialize to empty lists so the
  3036. // protocol/logs don't need to handle 'null' values.
  3037. authorizationIDs := make([]string, 0)
  3038. authorizedAccessTypes := make([]string, 0)
  3039. var stopTime time.Time
  3040. for i, authorization := range authorizations {
  3041. // This sanity check mitigates malicious clients causing excess CPU use.
  3042. if i >= MAX_AUTHORIZATIONS {
  3043. log.WithTrace().Warning("too many authorizations")
  3044. break
  3045. }
  3046. verifiedAuthorization, err := accesscontrol.VerifyAuthorization(
  3047. &sshClient.sshServer.support.Config.AccessControlVerificationKeyRing,
  3048. authorization)
  3049. if err != nil {
  3050. log.WithTraceFields(
  3051. LogFields{"error": err}).Warning("verify authorization failed")
  3052. continue
  3053. }
  3054. authorizationID := base64.StdEncoding.EncodeToString(verifiedAuthorization.ID)
  3055. if common.Contains(authorizedAccessTypes, verifiedAuthorization.AccessType) {
  3056. log.WithTraceFields(
  3057. LogFields{"accessType": verifiedAuthorization.AccessType}).Warning("duplicate authorization access type")
  3058. continue
  3059. }
  3060. authorizationIDs = append(authorizationIDs, authorizationID)
  3061. authorizedAccessTypes = append(authorizedAccessTypes, verifiedAuthorization.AccessType)
  3062. if stopTime.IsZero() || stopTime.After(verifiedAuthorization.Expires) {
  3063. stopTime = verifiedAuthorization.Expires
  3064. }
  3065. }
  3066. // Associate all verified authorizationIDs with this client's session ID.
  3067. // Handle cases where previous associations exist:
  3068. //
  3069. // - Multiple malicious clients reusing a single authorization. In this
  3070. // case, authorizations are revoked from the previous client.
  3071. //
  3072. // - The client reconnected with a new session ID due to user toggling.
  3073. // This case is expected due to server affinity. This cannot be
  3074. // distinguished from the previous case and the same action is taken;
  3075. // this will have no impact on a legitimate client as the previous
  3076. // session is dangling.
  3077. //
  3078. // - The client automatically reconnected with the same session ID. This
  3079. // case is not expected as sshServer.registerEstablishedClient
  3080. // synchronously calls sshClient.releaseAuthorizations; as a safe guard,
  3081. // this case is distinguished and no revocation action is taken.
  3082. sshClient.sshServer.authorizationSessionIDsMutex.Lock()
  3083. for _, authorizationID := range authorizationIDs {
  3084. sessionID, ok := sshClient.sshServer.authorizationSessionIDs[authorizationID]
  3085. if ok && sessionID != sshClient.sessionID {
  3086. logFields := LogFields{
  3087. "event_name": "irregular_tunnel",
  3088. "tunnel_error": "duplicate active authorization",
  3089. "duplicate_authorization_id": authorizationID,
  3090. }
  3091. // Log this using client, not peer, GeoIP data. In the case of
  3092. // in-proxy tunnel protocols, the client GeoIP fields will be None
  3093. // if a handshake does not complete. However, presense of a
  3094. // (duplicate) authorization implies that the handshake completed.
  3095. sshClient.getClientGeoIPData().SetClientLogFields(logFields)
  3096. duplicateClientGeoIPData := sshClient.sshServer.getGeoIPSessionCache(sessionID)
  3097. if duplicateClientGeoIPData != sshClient.getClientGeoIPData() {
  3098. duplicateClientGeoIPData.SetClientLogFieldsWithPrefix("duplicate_authorization_", logFields)
  3099. }
  3100. log.LogRawFieldsWithTimestamp(logFields)
  3101. // Invoke asynchronously to avoid deadlocks.
  3102. // TODO: invoke only once for each distinct sessionID?
  3103. go sshClient.sshServer.revokeClientAuthorizations(sessionID)
  3104. }
  3105. sshClient.sshServer.authorizationSessionIDs[authorizationID] = sshClient.sessionID
  3106. }
  3107. sshClient.sshServer.authorizationSessionIDsMutex.Unlock()
  3108. if len(authorizationIDs) > 0 {
  3109. sshClient.Lock()
  3110. // Make the authorizedAccessTypes available for traffic rules filtering.
  3111. sshClient.handshakeState.activeAuthorizationIDs = authorizationIDs
  3112. sshClient.handshakeState.authorizedAccessTypes = authorizedAccessTypes
  3113. // On exit, sshClient.runTunnel will call releaseAuthorizations, which
  3114. // will release the authorization IDs so the client can reconnect and
  3115. // present the same authorizations again. sshClient.runTunnel will
  3116. // also cancel the stopTimer in case it has not yet fired.
  3117. // Note: termination of the stopTimer goroutine is not synchronized.
  3118. sshClient.releaseAuthorizations = func() {
  3119. sshClient.sshServer.authorizationSessionIDsMutex.Lock()
  3120. for _, authorizationID := range authorizationIDs {
  3121. sessionID, ok := sshClient.sshServer.authorizationSessionIDs[authorizationID]
  3122. if ok && sessionID == sshClient.sessionID {
  3123. delete(sshClient.sshServer.authorizationSessionIDs, authorizationID)
  3124. }
  3125. }
  3126. sshClient.sshServer.authorizationSessionIDsMutex.Unlock()
  3127. }
  3128. sshClient.stopTimer = time.AfterFunc(
  3129. time.Until(stopTime),
  3130. func() {
  3131. sshClient.stop()
  3132. })
  3133. sshClient.Unlock()
  3134. }
  3135. upstreamBytesPerSecond, downstreamBytesPerSecond := sshClient.setTrafficRules()
  3136. sshClient.setOSLConfig()
  3137. // Set destination bytes metrics.
  3138. //
  3139. // Limitation: this is a one-time operation and doesn't get reset when
  3140. // tactics are hot-reloaded. This allows us to simply retain any
  3141. // destination byte counts accumulated and eventually log in
  3142. // server_tunnel, without having to deal with a destination change
  3143. // mid-tunnel. As typical tunnels are short, and destination changes can
  3144. // be applied gradually, handling mid-tunnel changes is not a priority.
  3145. sshClient.setDestinationBytesMetrics()
  3146. info := &handshakeStateInfo{
  3147. activeAuthorizationIDs: authorizationIDs,
  3148. authorizedAccessTypes: authorizedAccessTypes,
  3149. upstreamBytesPerSecond: upstreamBytesPerSecond,
  3150. downstreamBytesPerSecond: downstreamBytesPerSecond,
  3151. }
  3152. // Relay the steering IP to the API handshake handler.
  3153. if sshClient.additionalTransportData != nil {
  3154. info.steeringIP = sshClient.additionalTransportData.steeringIP
  3155. }
  3156. return info, nil
  3157. }
  3158. // getHandshaked returns whether the client has completed a handshake API
  3159. // request and whether the traffic rules that were selected after the
  3160. // handshake immediately exhaust the client.
  3161. //
  3162. // When the client is immediately exhausted it will be closed; but this
  3163. // takes effect asynchronously. The "exhausted" return value is used to
  3164. // prevent API requests by clients that will close.
  3165. func (sshClient *sshClient) getHandshaked() (bool, bool) {
  3166. sshClient.Lock()
  3167. defer sshClient.Unlock()
  3168. completed := sshClient.handshakeState.completed
  3169. exhausted := false
  3170. // Notes:
  3171. // - "Immediately exhausted" is when CloseAfterExhausted is set and
  3172. // either ReadUnthrottledBytes or WriteUnthrottledBytes starts from
  3173. // 0, so no bytes would be read or written. This check does not
  3174. // examine whether 0 bytes _remain_ in the ThrottledConn.
  3175. // - This check is made against the current traffic rules, which
  3176. // could have changed in a hot reload since the handshake.
  3177. if completed &&
  3178. *sshClient.trafficRules.RateLimits.CloseAfterExhausted &&
  3179. (*sshClient.trafficRules.RateLimits.ReadUnthrottledBytes == 0 ||
  3180. *sshClient.trafficRules.RateLimits.WriteUnthrottledBytes == 0) {
  3181. exhausted = true
  3182. }
  3183. return completed, exhausted
  3184. }
  3185. func (sshClient *sshClient) getDisableDiscovery() bool {
  3186. sshClient.Lock()
  3187. defer sshClient.Unlock()
  3188. return *sshClient.trafficRules.DisableDiscovery
  3189. }
  3190. func (sshClient *sshClient) updateAPIParameters(
  3191. apiParams common.APIParameters) {
  3192. sshClient.Lock()
  3193. defer sshClient.Unlock()
  3194. // Only update after handshake has initialized API params.
  3195. if !sshClient.handshakeState.completed {
  3196. return
  3197. }
  3198. for name, value := range apiParams {
  3199. sshClient.handshakeState.apiParams[name] = value
  3200. }
  3201. }
  3202. func (sshClient *sshClient) acceptDomainBytes() bool {
  3203. sshClient.Lock()
  3204. defer sshClient.Unlock()
  3205. // When the domain bytes checksum differs from the checksum sent to the
  3206. // client in the handshake response, the psinet regex configuration has
  3207. // changed. In this case, drop the stats so we don't continue to record
  3208. // stats as previously configured.
  3209. //
  3210. // Limitations:
  3211. // - The checksum comparison may result in dropping some stats for a
  3212. // domain that remains in the new configuration.
  3213. // - We don't push new regexs to the clients, so clients that remain
  3214. // connected will continue to send stats that will be dropped; and
  3215. // those clients will not send stats as newly configured until after
  3216. // reconnecting.
  3217. // - Due to the design of
  3218. // transferstats.ReportRecentBytesTransferredForServer in the client,
  3219. // the client may accumulate stats, reconnect before its next status
  3220. // request, get a new regex configuration, and then send the previously
  3221. // accumulated stats in its next status request. The checksum scheme
  3222. // won't prevent the reporting of those stats.
  3223. sponsorID, _ := getStringRequestParam(sshClient.handshakeState.apiParams, "sponsor_id")
  3224. domainBytesChecksum := sshClient.sshServer.support.PsinetDatabase.GetDomainBytesChecksum(sponsorID)
  3225. return bytes.Equal(sshClient.handshakeState.domainBytesChecksum, domainBytesChecksum)
  3226. }
  3227. // setOSLConfig resets the client's OSL seed state based on the latest OSL config
  3228. // As sshClient.oslClientSeedState may be reset by a concurrent goroutine,
  3229. // oslClientSeedState must only be accessed within the sshClient mutex.
  3230. func (sshClient *sshClient) setOSLConfig() {
  3231. sshClient.Lock()
  3232. defer sshClient.Unlock()
  3233. propagationChannelID, err := getStringRequestParam(
  3234. sshClient.handshakeState.apiParams, "propagation_channel_id")
  3235. if err != nil {
  3236. // This should not fail as long as client has sent valid handshake
  3237. return
  3238. }
  3239. // Use a cached seed state if one is found for the client's
  3240. // session ID. This enables resuming progress made in a previous
  3241. // tunnel.
  3242. // Note: go-cache is already concurency safe; the additional mutex
  3243. // is necessary to guarantee that Get/Delete is atomic; although in
  3244. // practice no two concurrent clients should ever supply the same
  3245. // session ID.
  3246. sshClient.sshServer.oslSessionCacheMutex.Lock()
  3247. oslClientSeedState, found := sshClient.sshServer.oslSessionCache.Get(sshClient.sessionID)
  3248. if found {
  3249. sshClient.sshServer.oslSessionCache.Delete(sshClient.sessionID)
  3250. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  3251. sshClient.oslClientSeedState = oslClientSeedState.(*osl.ClientSeedState)
  3252. sshClient.oslClientSeedState.Resume(sshClient.signalIssueSLOKs)
  3253. return
  3254. }
  3255. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  3256. // Two limitations when setOSLConfig() is invoked due to an
  3257. // OSL config hot reload:
  3258. //
  3259. // 1. any partial progress towards SLOKs is lost.
  3260. //
  3261. // 2. all existing osl.ClientSeedPortForwards for existing
  3262. // port forwards will not send progress to the new client
  3263. // seed state.
  3264. // Use the client, not peer, GeoIP data. In the case of in-proxy tunnel
  3265. // protocols, the client GeoIP fields will be populated using the
  3266. // original client IP already received, from the broker, in the handshake.
  3267. sshClient.oslClientSeedState = sshClient.sshServer.support.OSLConfig.NewClientSeedState(
  3268. sshClient.clientGeoIPData.Country,
  3269. propagationChannelID,
  3270. sshClient.signalIssueSLOKs)
  3271. }
  3272. // newClientSeedPortForward will return nil when no seeding is
  3273. // associated with the specified ipAddress.
  3274. func (sshClient *sshClient) newClientSeedPortForward(IPAddress net.IP) *osl.ClientSeedPortForward {
  3275. sshClient.Lock()
  3276. defer sshClient.Unlock()
  3277. // Will not be initialized before handshake.
  3278. if sshClient.oslClientSeedState == nil {
  3279. return nil
  3280. }
  3281. return sshClient.oslClientSeedState.NewClientSeedPortForward(IPAddress)
  3282. }
  3283. // getOSLSeedPayload returns a payload containing all seeded SLOKs for
  3284. // this client's session.
  3285. func (sshClient *sshClient) getOSLSeedPayload() *osl.SeedPayload {
  3286. sshClient.Lock()
  3287. defer sshClient.Unlock()
  3288. // Will not be initialized before handshake.
  3289. if sshClient.oslClientSeedState == nil {
  3290. return &osl.SeedPayload{SLOKs: make([]*osl.SLOK, 0)}
  3291. }
  3292. return sshClient.oslClientSeedState.GetSeedPayload()
  3293. }
  3294. func (sshClient *sshClient) clearOSLSeedPayload() {
  3295. sshClient.Lock()
  3296. defer sshClient.Unlock()
  3297. sshClient.oslClientSeedState.ClearSeedPayload()
  3298. }
  3299. func (sshClient *sshClient) setDestinationBytesMetrics() {
  3300. sshClient.Lock()
  3301. defer sshClient.Unlock()
  3302. // Limitation: the server-side tactics cache is used to avoid the overhead
  3303. // of an additional tactics filtering per tunnel. As this cache is
  3304. // designed for GeoIP filtering only, handshake API parameters are not
  3305. // applied to tactics filtering in this case.
  3306. tacticsCache := sshClient.sshServer.support.ServerTacticsParametersCache
  3307. if tacticsCache == nil {
  3308. return
  3309. }
  3310. // Use the client, not peer, GeoIP data. In the case of in-proxy tunnel
  3311. // protocols, the client GeoIP fields will be populated using the
  3312. // original client IP already received, from the broker, in the handshake.
  3313. p, err := tacticsCache.Get(sshClient.clientGeoIPData)
  3314. if err != nil {
  3315. log.WithTraceFields(LogFields{"error": err}).Warning("get tactics failed")
  3316. return
  3317. }
  3318. if p.IsNil() {
  3319. return
  3320. }
  3321. sshClient.destinationBytesMetricsASN = p.String(parameters.DestinationBytesMetricsASN)
  3322. }
  3323. func (sshClient *sshClient) newDestinationBytesMetricsUpdater(portForwardType int, IPAddress net.IP) *destinationBytesMetrics {
  3324. sshClient.Lock()
  3325. defer sshClient.Unlock()
  3326. if sshClient.destinationBytesMetricsASN == "" {
  3327. return nil
  3328. }
  3329. if sshClient.sshServer.support.GeoIPService.LookupISPForIP(IPAddress).ASN != sshClient.destinationBytesMetricsASN {
  3330. return nil
  3331. }
  3332. if portForwardType == portForwardTypeTCP {
  3333. return &sshClient.tcpDestinationBytesMetrics
  3334. }
  3335. return &sshClient.udpDestinationBytesMetrics
  3336. }
  3337. func (sshClient *sshClient) getActivityUpdaters(portForwardType int, IPAddress net.IP) []common.ActivityUpdater {
  3338. var updaters []common.ActivityUpdater
  3339. clientSeedPortForward := sshClient.newClientSeedPortForward(IPAddress)
  3340. if clientSeedPortForward != nil {
  3341. updaters = append(updaters, clientSeedPortForward)
  3342. }
  3343. destinationBytesMetrics := sshClient.newDestinationBytesMetricsUpdater(portForwardType, IPAddress)
  3344. if destinationBytesMetrics != nil {
  3345. updaters = append(updaters, destinationBytesMetrics)
  3346. }
  3347. return updaters
  3348. }
  3349. // setTrafficRules resets the client's traffic rules based on the latest server config
  3350. // and client properties. As sshClient.trafficRules may be reset by a concurrent
  3351. // goroutine, trafficRules must only be accessed within the sshClient mutex.
  3352. func (sshClient *sshClient) setTrafficRules() (int64, int64) {
  3353. sshClient.Lock()
  3354. defer sshClient.Unlock()
  3355. isFirstTunnelInSession := sshClient.isFirstTunnelInSession &&
  3356. sshClient.handshakeState.establishedTunnelsCount == 0
  3357. // In the case of in-proxy tunnel protocols, the client GeoIP data is None
  3358. // until the handshake completes. Pre-handhake, the rate limit is
  3359. // determined by EstablishmentRead/WriteBytesPerSecond, which default to
  3360. // unthrottled, the recommended setting; in addition, no port forwards
  3361. // are permitted until after the handshake completes, at which time
  3362. // setTrafficRules will be called again with the client GeoIP data
  3363. // populated using the original client IP received from the in-proxy
  3364. // broker.
  3365. sshClient.trafficRules = sshClient.sshServer.support.TrafficRulesSet.GetTrafficRules(
  3366. isFirstTunnelInSession,
  3367. sshClient.tunnelProtocol,
  3368. sshClient.clientGeoIPData,
  3369. sshClient.handshakeState)
  3370. if sshClient.throttledConn != nil {
  3371. // Any existing throttling state is reset.
  3372. sshClient.throttledConn.SetLimits(
  3373. sshClient.trafficRules.RateLimits.CommonRateLimits(
  3374. sshClient.handshakeState.completed))
  3375. }
  3376. return *sshClient.trafficRules.RateLimits.ReadBytesPerSecond,
  3377. *sshClient.trafficRules.RateLimits.WriteBytesPerSecond
  3378. }
  3379. func (sshClient *sshClient) rateLimits() common.RateLimits {
  3380. sshClient.Lock()
  3381. defer sshClient.Unlock()
  3382. return sshClient.trafficRules.RateLimits.CommonRateLimits(
  3383. sshClient.handshakeState.completed)
  3384. }
  3385. func (sshClient *sshClient) idleTCPPortForwardTimeout() time.Duration {
  3386. sshClient.Lock()
  3387. defer sshClient.Unlock()
  3388. return time.Duration(*sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds) * time.Millisecond
  3389. }
  3390. func (sshClient *sshClient) idleUDPPortForwardTimeout() time.Duration {
  3391. sshClient.Lock()
  3392. defer sshClient.Unlock()
  3393. return time.Duration(*sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds) * time.Millisecond
  3394. }
  3395. func (sshClient *sshClient) setTCPPortForwardDialingAvailableSignal(signal context.CancelFunc) {
  3396. sshClient.Lock()
  3397. defer sshClient.Unlock()
  3398. sshClient.tcpPortForwardDialingAvailableSignal = signal
  3399. }
  3400. const (
  3401. portForwardTypeTCP = iota
  3402. portForwardTypeUDP
  3403. )
  3404. func (sshClient *sshClient) isPortForwardPermitted(
  3405. portForwardType int,
  3406. remoteIP net.IP,
  3407. port int) bool {
  3408. // Disallow connection to bogons.
  3409. //
  3410. // As a security measure, this is a failsafe. The server should be run on a
  3411. // host with correctly configured firewall rules.
  3412. //
  3413. // This check also avoids spurious disallowed traffic alerts for destinations
  3414. // that are impossible to reach.
  3415. if !sshClient.sshServer.support.Config.AllowBogons && common.IsBogon(remoteIP) {
  3416. return false
  3417. }
  3418. // Blocklist check.
  3419. //
  3420. // Limitation: isPortForwardPermitted is not called in transparent DNS
  3421. // forwarding cases. As the destination IP address is rewritten in these
  3422. // cases, a blocklist entry won't be dialed in any case. However, no logs
  3423. // will be recorded.
  3424. if !sshClient.isIPPermitted(remoteIP) {
  3425. return false
  3426. }
  3427. // Don't lock before calling logBlocklistHits.
  3428. // Unlock before calling enqueueDisallowedTrafficAlertRequest/log.
  3429. sshClient.Lock()
  3430. allowed := true
  3431. // Client must complete handshake before port forwards are permitted.
  3432. if !sshClient.handshakeState.completed {
  3433. allowed = false
  3434. }
  3435. if allowed {
  3436. // Traffic rules checks.
  3437. switch portForwardType {
  3438. case portForwardTypeTCP:
  3439. if !sshClient.trafficRules.AllowTCPPort(
  3440. sshClient.sshServer.support.GeoIPService, remoteIP, port) {
  3441. allowed = false
  3442. }
  3443. case portForwardTypeUDP:
  3444. if !sshClient.trafficRules.AllowUDPPort(
  3445. sshClient.sshServer.support.GeoIPService, remoteIP, port) {
  3446. allowed = false
  3447. }
  3448. }
  3449. }
  3450. sshClient.Unlock()
  3451. if allowed {
  3452. return true
  3453. }
  3454. switch portForwardType {
  3455. case portForwardTypeTCP:
  3456. sshClient.updateQualityMetricsWithTCPRejectedDisallowed()
  3457. case portForwardTypeUDP:
  3458. sshClient.updateQualityMetricsWithUDPRejectedDisallowed()
  3459. }
  3460. sshClient.enqueueDisallowedTrafficAlertRequest()
  3461. log.WithTraceFields(
  3462. LogFields{
  3463. "type": portForwardType,
  3464. "port": port,
  3465. }).Debug("port forward denied by traffic rules")
  3466. return false
  3467. }
  3468. // isDomainPermitted returns true when the specified domain may be resolved
  3469. // and returns false and a reject reason otherwise.
  3470. func (sshClient *sshClient) isDomainPermitted(domain string) (bool, string) {
  3471. // We're not doing comprehensive validation, to avoid overhead per port
  3472. // forward. This is a simple sanity check to ensure we don't process
  3473. // blantantly invalid input.
  3474. //
  3475. // TODO: validate with dns.IsDomainName?
  3476. if len(domain) > 255 {
  3477. return false, "invalid domain name"
  3478. }
  3479. tags := sshClient.sshServer.support.Blocklist.LookupDomain(domain)
  3480. if len(tags) > 0 {
  3481. sshClient.logBlocklistHits(nil, domain, tags)
  3482. if sshClient.sshServer.support.Config.BlocklistActive {
  3483. // Actively alert and block
  3484. sshClient.enqueueUnsafeTrafficAlertRequest(tags)
  3485. return false, "port forward not permitted"
  3486. }
  3487. }
  3488. return true, ""
  3489. }
  3490. func (sshClient *sshClient) isIPPermitted(remoteIP net.IP) bool {
  3491. tags := sshClient.sshServer.support.Blocklist.LookupIP(remoteIP)
  3492. if len(tags) > 0 {
  3493. sshClient.logBlocklistHits(remoteIP, "", tags)
  3494. if sshClient.sshServer.support.Config.BlocklistActive {
  3495. // Actively alert and block
  3496. sshClient.enqueueUnsafeTrafficAlertRequest(tags)
  3497. return false
  3498. }
  3499. }
  3500. return true
  3501. }
  3502. func (sshClient *sshClient) isTCPDialingPortForwardLimitExceeded() bool {
  3503. sshClient.Lock()
  3504. defer sshClient.Unlock()
  3505. state := &sshClient.tcpTrafficState
  3506. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  3507. if max > 0 && state.concurrentDialingPortForwardCount >= int64(max) {
  3508. return true
  3509. }
  3510. return false
  3511. }
  3512. func (sshClient *sshClient) getTCPPortForwardQueueSize() int {
  3513. sshClient.Lock()
  3514. defer sshClient.Unlock()
  3515. return *sshClient.trafficRules.MaxTCPPortForwardCount +
  3516. *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  3517. }
  3518. func (sshClient *sshClient) getDialTCPPortForwardTimeoutMilliseconds() int {
  3519. sshClient.Lock()
  3520. defer sshClient.Unlock()
  3521. return *sshClient.trafficRules.DialTCPPortForwardTimeoutMilliseconds
  3522. }
  3523. func (sshClient *sshClient) dialingTCPPortForward() {
  3524. sshClient.Lock()
  3525. defer sshClient.Unlock()
  3526. state := &sshClient.tcpTrafficState
  3527. state.concurrentDialingPortForwardCount += 1
  3528. if state.concurrentDialingPortForwardCount > state.peakConcurrentDialingPortForwardCount {
  3529. state.peakConcurrentDialingPortForwardCount = state.concurrentDialingPortForwardCount
  3530. }
  3531. }
  3532. func (sshClient *sshClient) abortedTCPPortForward() {
  3533. sshClient.Lock()
  3534. defer sshClient.Unlock()
  3535. sshClient.tcpTrafficState.concurrentDialingPortForwardCount -= 1
  3536. }
  3537. func (sshClient *sshClient) allocatePortForward(portForwardType int) bool {
  3538. sshClient.Lock()
  3539. defer sshClient.Unlock()
  3540. // Check if at port forward limit. The subsequent counter
  3541. // changes must be atomic with the limit check to ensure
  3542. // the counter never exceeds the limit in the case of
  3543. // concurrent allocations.
  3544. var max int
  3545. var state *trafficState
  3546. if portForwardType == portForwardTypeTCP {
  3547. max = *sshClient.trafficRules.MaxTCPPortForwardCount
  3548. state = &sshClient.tcpTrafficState
  3549. } else {
  3550. max = *sshClient.trafficRules.MaxUDPPortForwardCount
  3551. state = &sshClient.udpTrafficState
  3552. }
  3553. if max > 0 && state.concurrentPortForwardCount >= int64(max) {
  3554. return false
  3555. }
  3556. // Update port forward counters.
  3557. if portForwardType == portForwardTypeTCP {
  3558. // Assumes TCP port forwards called dialingTCPPortForward
  3559. state.concurrentDialingPortForwardCount -= 1
  3560. if sshClient.tcpPortForwardDialingAvailableSignal != nil {
  3561. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  3562. if max <= 0 || state.concurrentDialingPortForwardCount < int64(max) {
  3563. sshClient.tcpPortForwardDialingAvailableSignal()
  3564. }
  3565. }
  3566. }
  3567. state.concurrentPortForwardCount += 1
  3568. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  3569. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  3570. }
  3571. state.totalPortForwardCount += 1
  3572. return true
  3573. }
  3574. // establishedPortForward increments the concurrent port
  3575. // forward counter. closedPortForward decrements it, so it
  3576. // must always be called for each establishedPortForward
  3577. // call.
  3578. //
  3579. // When at the limit of established port forwards, the LRU
  3580. // existing port forward is closed to make way for the newly
  3581. // established one. There can be a minor delay as, in addition
  3582. // to calling Close() on the port forward net.Conn,
  3583. // establishedPortForward waits for the LRU's closedPortForward()
  3584. // call which will decrement the concurrent counter. This
  3585. // ensures all resources associated with the LRU (socket,
  3586. // goroutine) are released or will very soon be released before
  3587. // proceeding.
  3588. func (sshClient *sshClient) establishedPortForward(
  3589. portForwardType int, portForwardLRU *common.LRUConns) {
  3590. // Do not lock sshClient here.
  3591. var state *trafficState
  3592. if portForwardType == portForwardTypeTCP {
  3593. state = &sshClient.tcpTrafficState
  3594. } else {
  3595. state = &sshClient.udpTrafficState
  3596. }
  3597. // When the maximum number of port forwards is already
  3598. // established, close the LRU. CloseOldest will call
  3599. // Close on the port forward net.Conn. Both TCP and
  3600. // UDP port forwards have handler goroutines that may
  3601. // be blocked calling Read on the net.Conn. Close will
  3602. // eventually interrupt the Read and cause the handlers
  3603. // to exit, but not immediately. So the following logic
  3604. // waits for a LRU handler to be interrupted and signal
  3605. // availability.
  3606. //
  3607. // Notes:
  3608. //
  3609. // - the port forward limit can change via a traffic
  3610. // rules hot reload; the condition variable handles
  3611. // this case whereas a channel-based semaphore would
  3612. // not.
  3613. //
  3614. // - if a number of goroutines exceeding the total limit
  3615. // arrive here all concurrently, some CloseOldest() calls
  3616. // will have no effect as there can be less existing port
  3617. // forwards than new ones. In this case, the new port
  3618. // forward will be delayed. This is highly unlikely in
  3619. // practise since UDP calls to establishedPortForward are
  3620. // serialized and TCP calls are limited by the dial
  3621. // queue/count.
  3622. if !sshClient.allocatePortForward(portForwardType) {
  3623. portForwardLRU.CloseOldest()
  3624. log.WithTrace().Debug("closed LRU port forward")
  3625. state.availablePortForwardCond.L.Lock()
  3626. for !sshClient.allocatePortForward(portForwardType) {
  3627. state.availablePortForwardCond.Wait()
  3628. }
  3629. state.availablePortForwardCond.L.Unlock()
  3630. }
  3631. }
  3632. func (sshClient *sshClient) closedPortForward(
  3633. portForwardType int, bytesUp, bytesDown int64) {
  3634. sshClient.Lock()
  3635. var state *trafficState
  3636. if portForwardType == portForwardTypeTCP {
  3637. state = &sshClient.tcpTrafficState
  3638. } else {
  3639. state = &sshClient.udpTrafficState
  3640. }
  3641. state.concurrentPortForwardCount -= 1
  3642. state.bytesUp += bytesUp
  3643. state.bytesDown += bytesDown
  3644. sshClient.Unlock()
  3645. // Signal any goroutine waiting in establishedPortForward
  3646. // that an established port forward slot is available.
  3647. state.availablePortForwardCond.Signal()
  3648. }
  3649. func (sshClient *sshClient) updateQualityMetricsWithDialResult(
  3650. tcpPortForwardDialSuccess bool, dialDuration time.Duration, IP net.IP) {
  3651. sshClient.Lock()
  3652. defer sshClient.Unlock()
  3653. if tcpPortForwardDialSuccess {
  3654. sshClient.qualityMetrics.TCPPortForwardDialedCount += 1
  3655. sshClient.qualityMetrics.TCPPortForwardDialedDuration += dialDuration
  3656. if IP.To4() != nil {
  3657. sshClient.qualityMetrics.TCPIPv4PortForwardDialedCount += 1
  3658. sshClient.qualityMetrics.TCPIPv4PortForwardDialedDuration += dialDuration
  3659. } else if IP != nil {
  3660. sshClient.qualityMetrics.TCPIPv6PortForwardDialedCount += 1
  3661. sshClient.qualityMetrics.TCPIPv6PortForwardDialedDuration += dialDuration
  3662. }
  3663. } else {
  3664. sshClient.qualityMetrics.TCPPortForwardFailedCount += 1
  3665. sshClient.qualityMetrics.TCPPortForwardFailedDuration += dialDuration
  3666. if IP.To4() != nil {
  3667. sshClient.qualityMetrics.TCPIPv4PortForwardFailedCount += 1
  3668. sshClient.qualityMetrics.TCPIPv4PortForwardFailedDuration += dialDuration
  3669. } else if IP != nil {
  3670. sshClient.qualityMetrics.TCPIPv6PortForwardFailedCount += 1
  3671. sshClient.qualityMetrics.TCPIPv6PortForwardFailedDuration += dialDuration
  3672. }
  3673. }
  3674. }
  3675. func (sshClient *sshClient) updateQualityMetricsWithRejectedDialingLimit() {
  3676. sshClient.Lock()
  3677. defer sshClient.Unlock()
  3678. sshClient.qualityMetrics.TCPPortForwardRejectedDialingLimitCount += 1
  3679. }
  3680. func (sshClient *sshClient) updateQualityMetricsWithTCPRejectedDisallowed() {
  3681. sshClient.Lock()
  3682. defer sshClient.Unlock()
  3683. sshClient.qualityMetrics.TCPPortForwardRejectedDisallowedCount += 1
  3684. }
  3685. func (sshClient *sshClient) updateQualityMetricsWithUDPRejectedDisallowed() {
  3686. sshClient.Lock()
  3687. defer sshClient.Unlock()
  3688. sshClient.qualityMetrics.UDPPortForwardRejectedDisallowedCount += 1
  3689. }
  3690. func (sshClient *sshClient) updateQualityMetricsWithDNSResult(
  3691. success bool, duration time.Duration, resolverIP net.IP) {
  3692. sshClient.Lock()
  3693. defer sshClient.Unlock()
  3694. resolver := ""
  3695. if resolverIP != nil {
  3696. resolver = resolverIP.String()
  3697. }
  3698. if success {
  3699. sshClient.qualityMetrics.DNSCount["ALL"] += 1
  3700. sshClient.qualityMetrics.DNSDuration["ALL"] += duration
  3701. if resolver != "" {
  3702. sshClient.qualityMetrics.DNSCount[resolver] += 1
  3703. sshClient.qualityMetrics.DNSDuration[resolver] += duration
  3704. }
  3705. } else {
  3706. sshClient.qualityMetrics.DNSFailedCount["ALL"] += 1
  3707. sshClient.qualityMetrics.DNSFailedDuration["ALL"] += duration
  3708. if resolver != "" {
  3709. sshClient.qualityMetrics.DNSFailedCount[resolver] += 1
  3710. sshClient.qualityMetrics.DNSFailedDuration[resolver] += duration
  3711. }
  3712. }
  3713. }
  3714. func (sshClient *sshClient) handleTCPChannel(
  3715. remainingDialTimeout time.Duration,
  3716. hostToConnect string,
  3717. portToConnect int,
  3718. doSplitTunnel bool,
  3719. newChannel ssh.NewChannel) {
  3720. // Assumptions:
  3721. // - sshClient.dialingTCPPortForward() has been called
  3722. // - remainingDialTimeout > 0
  3723. established := false
  3724. defer func() {
  3725. if !established {
  3726. sshClient.abortedTCPPortForward()
  3727. }
  3728. }()
  3729. // Validate the domain name and check the domain blocklist before dialing.
  3730. //
  3731. // The IP blocklist is checked in isPortForwardPermitted, which also provides
  3732. // IP blocklist checking for the packet tunnel code path. When hostToConnect
  3733. // is an IP address, the following hostname resolution step effectively
  3734. // performs no actions and next immediate step is the isPortForwardPermitted
  3735. // check.
  3736. //
  3737. // Limitation: this case handles port forwards where the client sends the
  3738. // destination domain in the SSH port forward request but does not currently
  3739. // handle DNS-over-TCP; in the DNS-over-TCP case, a client may bypass the
  3740. // block list check.
  3741. if net.ParseIP(hostToConnect) == nil {
  3742. ok, rejectMessage := sshClient.isDomainPermitted(hostToConnect)
  3743. if !ok {
  3744. // Note: not recording a port forward failure in this case
  3745. sshClient.rejectNewChannel(newChannel, rejectMessage)
  3746. return
  3747. }
  3748. }
  3749. // Dial the remote address.
  3750. //
  3751. // Hostname resolution is performed explicitly, as a separate step, as the
  3752. // target IP address is used for traffic rules (AllowSubnets), OSL seed
  3753. // progress, and IP address blocklists.
  3754. //
  3755. // Contexts are used for cancellation (via sshClient.runCtx, which is
  3756. // cancelled when the client is stopping) and timeouts.
  3757. dialStartTime := time.Now()
  3758. IP := net.ParseIP(hostToConnect)
  3759. if IP == nil {
  3760. // Resolve the hostname
  3761. log.WithTraceFields(LogFields{"hostToConnect": hostToConnect}).Debug("resolving")
  3762. ctx, cancelCtx := context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  3763. IPs, err := (&net.Resolver{}).LookupIPAddr(ctx, hostToConnect)
  3764. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  3765. resolveElapsedTime := time.Since(dialStartTime)
  3766. // Record DNS metrics. If LookupIPAddr returns net.DNSError.IsNotFound, this
  3767. // is "no such host" and not a DNS failure. Limitation: the resolver IP is
  3768. // not known.
  3769. dnsErr, ok := err.(*net.DNSError)
  3770. dnsNotFound := ok && dnsErr.IsNotFound
  3771. dnsSuccess := err == nil || dnsNotFound
  3772. sshClient.updateQualityMetricsWithDNSResult(dnsSuccess, resolveElapsedTime, nil)
  3773. // IPv4 is preferred in case the host has limited IPv6 routing. IPv6 is
  3774. // selected and attempted only when there's no IPv4 option.
  3775. // TODO: shuffle list to try other IPs?
  3776. for _, ip := range IPs {
  3777. if ip.IP.To4() != nil {
  3778. IP = ip.IP
  3779. break
  3780. }
  3781. }
  3782. if IP == nil && len(IPs) > 0 {
  3783. // If there are no IPv4 IPs, the first IP is IPv6.
  3784. IP = IPs[0].IP
  3785. }
  3786. if err == nil && IP == nil {
  3787. err = std_errors.New("no IP address")
  3788. }
  3789. if err != nil {
  3790. // Record a port forward failure
  3791. sshClient.updateQualityMetricsWithDialResult(false, resolveElapsedTime, IP)
  3792. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("LookupIP failed: %s", err))
  3793. return
  3794. }
  3795. remainingDialTimeout -= resolveElapsedTime
  3796. }
  3797. if remainingDialTimeout <= 0 {
  3798. sshClient.rejectNewChannel(newChannel, "TCP port forward timed out resolving")
  3799. return
  3800. }
  3801. // When the client has indicated split tunnel mode and when the channel is
  3802. // not of type protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE, check if the
  3803. // client and the port forward destination are in the same GeoIP country. If
  3804. // so, reject the port forward with a distinct response code that indicates
  3805. // to the client that this port forward should be performed locally, direct
  3806. // and untunneled.
  3807. //
  3808. // Clients are expected to cache untunneled responses to avoid this round
  3809. // trip in the immediate future and reduce server load.
  3810. //
  3811. // When the countries differ, immediately proceed with the standard port
  3812. // forward. No additional round trip is required.
  3813. //
  3814. // If either GeoIP country is "None", one or both countries are unknown
  3815. // and there is no match.
  3816. //
  3817. // Traffic rules, such as allowed ports, are not enforced for port forward
  3818. // destinations classified as untunneled.
  3819. //
  3820. // Domain and IP blocklists still apply to port forward destinations
  3821. // classified as untunneled.
  3822. //
  3823. // The client's use of split tunnel mode is logged in server_tunnel metrics
  3824. // as the boolean value split_tunnel. As they may indicate some information
  3825. // about browsing activity, no other split tunnel metrics are logged.
  3826. if doSplitTunnel {
  3827. destinationGeoIPData := sshClient.sshServer.support.GeoIPService.LookupIP(IP)
  3828. // Use the client, not peer, GeoIP data. In the case of in-proxy tunnel
  3829. // protocols, the client GeoIP fields will be populated using the
  3830. // original client IP already received, from the broker, in the handshake.
  3831. clientGeoIPData := sshClient.getClientGeoIPData()
  3832. if clientGeoIPData.Country != GEOIP_UNKNOWN_VALUE &&
  3833. sshClient.handshakeState.splitTunnelLookup.lookup(
  3834. destinationGeoIPData.Country) {
  3835. // Since isPortForwardPermitted is not called in this case, explicitly call
  3836. // ipBlocklistCheck. The domain blocklist case is handled above.
  3837. if !sshClient.isIPPermitted(IP) {
  3838. // Note: not recording a port forward failure in this case
  3839. sshClient.rejectNewChannel(newChannel, "port forward not permitted")
  3840. return
  3841. }
  3842. newChannel.Reject(protocol.CHANNEL_REJECT_REASON_SPLIT_TUNNEL, "")
  3843. return
  3844. }
  3845. }
  3846. // Enforce traffic rules, using the resolved IP address.
  3847. if !sshClient.isPortForwardPermitted(
  3848. portForwardTypeTCP, IP, portToConnect) {
  3849. // Note: not recording a port forward failure in this case
  3850. sshClient.rejectNewChannel(newChannel, "port forward not permitted")
  3851. return
  3852. }
  3853. // TCP dial.
  3854. remoteAddr := net.JoinHostPort(IP.String(), strconv.Itoa(portToConnect))
  3855. log.WithTraceFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  3856. ctx, cancelCtx := context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  3857. fwdConn, err := (&net.Dialer{}).DialContext(ctx, "tcp", remoteAddr)
  3858. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  3859. // Record port forward success or failure
  3860. sshClient.updateQualityMetricsWithDialResult(err == nil, time.Since(dialStartTime), IP)
  3861. if err != nil {
  3862. // Monitor for low resource error conditions
  3863. sshClient.sshServer.monitorPortForwardDialError(err)
  3864. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("DialTimeout failed: %s", err))
  3865. return
  3866. }
  3867. // The upstream TCP port forward connection has been established. Schedule
  3868. // some cleanup and notify the SSH client that the channel is accepted.
  3869. defer fwdConn.Close()
  3870. fwdChannel, requests, err := newChannel.Accept()
  3871. if err != nil {
  3872. if !isExpectedTunnelIOError(err) {
  3873. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  3874. }
  3875. return
  3876. }
  3877. go ssh.DiscardRequests(requests)
  3878. defer fwdChannel.Close()
  3879. // Release the dialing slot and acquire an established slot.
  3880. //
  3881. // establishedPortForward increments the concurrent TCP port
  3882. // forward counter and closes the LRU existing TCP port forward
  3883. // when already at the limit.
  3884. //
  3885. // Known limitations:
  3886. //
  3887. // - Closed LRU TCP sockets will enter the TIME_WAIT state,
  3888. // continuing to consume some resources.
  3889. sshClient.establishedPortForward(portForwardTypeTCP, sshClient.tcpPortForwardLRU)
  3890. // "established = true" cancels the deferred abortedTCPPortForward()
  3891. established = true
  3892. // TODO: 64-bit alignment? https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  3893. var bytesUp, bytesDown int64
  3894. defer func() {
  3895. sshClient.closedPortForward(
  3896. portForwardTypeTCP, atomic.LoadInt64(&bytesUp), atomic.LoadInt64(&bytesDown))
  3897. }()
  3898. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  3899. defer lruEntry.Remove()
  3900. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  3901. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  3902. // forward if both reads and writes have been idle for the specified
  3903. // duration.
  3904. fwdConn, err = common.NewActivityMonitoredConn(
  3905. fwdConn,
  3906. sshClient.idleTCPPortForwardTimeout(),
  3907. true,
  3908. lruEntry,
  3909. sshClient.getActivityUpdaters(portForwardTypeTCP, IP)...)
  3910. if err != nil {
  3911. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  3912. return
  3913. }
  3914. // Relay channel to forwarded connection.
  3915. log.WithTraceFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  3916. // TODO: relay errors to fwdChannel.Stderr()?
  3917. relayWaitGroup := new(sync.WaitGroup)
  3918. relayWaitGroup.Add(1)
  3919. go func() {
  3920. defer relayWaitGroup.Done()
  3921. // io.Copy allocates a 32K temporary buffer, and each port forward relay
  3922. // uses two of these buffers; using common.CopyBuffer with a smaller buffer
  3923. // reduces the overall memory footprint.
  3924. bytes, err := common.CopyBuffer(
  3925. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  3926. atomic.AddInt64(&bytesDown, bytes)
  3927. if err != nil && err != io.EOF {
  3928. // Debug since errors such as "connection reset by peer" occur during normal operation
  3929. log.WithTraceFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  3930. }
  3931. // Interrupt upstream io.Copy when downstream is shutting down.
  3932. // TODO: this is done to quickly cleanup the port forward when
  3933. // fwdConn has a read timeout, but is it clean -- upstream may still
  3934. // be flowing?
  3935. fwdChannel.Close()
  3936. }()
  3937. bytes, err := common.CopyBuffer(
  3938. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  3939. atomic.AddInt64(&bytesUp, bytes)
  3940. if err != nil && err != io.EOF {
  3941. log.WithTraceFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  3942. }
  3943. // Shutdown special case: fwdChannel will be closed and return EOF when
  3944. // the SSH connection is closed, but we need to explicitly close fwdConn
  3945. // to interrupt the downstream io.Copy, which may be blocked on a
  3946. // fwdConn.Read().
  3947. fwdConn.Close()
  3948. relayWaitGroup.Wait()
  3949. log.WithTraceFields(
  3950. LogFields{
  3951. "remoteAddr": remoteAddr,
  3952. "bytesUp": atomic.LoadInt64(&bytesUp),
  3953. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  3954. }