tunnelServer.go 131 KB

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