tunnelServer.go 114 KB

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