tunnelServer.go 100 KB

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