tunnelServer.go 153 KB

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