tunnelServer.go 122 KB

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