tunnelServer.go 118 KB

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