tunnelServer.go 117 KB

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