tunnelServer.go 86 KB

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