tunnelServer.go 173 KB

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