tunnelServer.go 102 KB

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