tunnelServer.go 147 KB

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