tunnelServer.go 86 KB

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