tunnelServer.go 124 KB

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