tunnelServer.go 99 KB

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