tunnelServer.go 134 KB

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