tunnelServer.go 74 KB

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