tunnelServer.go 154 KB

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