tunnelServer.go 96 KB

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