tunnelServer.go 165 KB

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