tunnelServer.go 147 KB

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