tunnelServer.go 148 KB

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