tunnelServer.go 189 KB

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