tunnelServer.go 167 KB

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