tunnelServer.go 98 KB

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