tunnelServer.go 140 KB

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