tunnelServer.go 88 KB

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