tunnelServer.go 102 KB

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