tunnelServer.go 123 KB

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