tunnelServer.go 74 KB

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