tunnelServer.go 83 KB

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