tunnelServer.go 133 KB

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