tunnelServer.go 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472
  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. geoIPData := sshServer.support.GeoIPService.Lookup(
  869. common.IPAddressFromAddr(clientAddr))
  870. sshServer.registerAcceptedClient(tunnelProtocol, geoIPData.Country)
  871. defer sshServer.unregisterAcceptedClient(tunnelProtocol, geoIPData.Country)
  872. // When configured, enforce a cap on the number of concurrent SSH
  873. // handshakes. This limits load spikes on busy servers when many clients
  874. // attempt to connect at once. Wait a short time, SSH_BEGIN_HANDSHAKE_TIMEOUT,
  875. // to acquire; waiting will avoid immediately creating more load on another
  876. // server in the network when the client tries a new candidate. Disconnect the
  877. // client when that wait time is exceeded.
  878. //
  879. // This mechanism limits memory allocations and CPU usage associated with the
  880. // SSH handshake. At this point, new direct TCP connections or new meek
  881. // connections, with associated resource usage, are already established. Those
  882. // connections are expected to be rate or load limited using other mechanisms.
  883. //
  884. // TODO:
  885. //
  886. // - deduct time spent acquiring the semaphore from SSH_HANDSHAKE_TIMEOUT in
  887. // sshClient.run, since the client is also applying an SSH handshake timeout
  888. // and won't exclude time spent waiting.
  889. // - each call to sshServer.handleClient (in sshServer.runListener) is invoked
  890. // in its own goroutine, but shutdown doesn't synchronously await these
  891. // goroutnes. Once this is synchronizes, the following context.WithTimeout
  892. // should use an sshServer parent context to ensure blocking acquires
  893. // interrupt immediately upon shutdown.
  894. var onSSHHandshakeFinished func()
  895. if sshServer.support.Config.MaxConcurrentSSHHandshakes > 0 {
  896. ctx, cancelFunc := context.WithTimeout(
  897. context.Background(),
  898. sshServer.support.Config.sshBeginHandshakeTimeout)
  899. defer cancelFunc()
  900. err := sshServer.concurrentSSHHandshakes.Acquire(ctx, 1)
  901. if err != nil {
  902. clientConn.Close()
  903. // This is a debug log as the only possible error is context timeout.
  904. log.WithTraceFields(LogFields{"error": err}).Debug(
  905. "acquire SSH handshake semaphore failed")
  906. return
  907. }
  908. onSSHHandshakeFinished = func() {
  909. sshServer.concurrentSSHHandshakes.Release(1)
  910. }
  911. }
  912. sshClient := newSshClient(
  913. sshServer,
  914. sshListener,
  915. tunnelProtocol,
  916. geoIPData)
  917. // sshClient.run _must_ call onSSHHandshakeFinished to release the semaphore:
  918. // in any error case; or, as soon as the SSH handshake phase has successfully
  919. // completed.
  920. sshClient.run(clientConn, onSSHHandshakeFinished)
  921. }
  922. func (sshServer *sshServer) monitorPortForwardDialError(err error) {
  923. // "err" is the error returned from a failed TCP or UDP port
  924. // forward dial. Certain system error codes indicate low resource
  925. // conditions: insufficient file descriptors, ephemeral ports, or
  926. // memory. For these cases, log an alert.
  927. // TODO: also temporarily suspend new clients
  928. // Note: don't log net.OpError.Error() as the full error string
  929. // may contain client destination addresses.
  930. opErr, ok := err.(*net.OpError)
  931. if ok {
  932. if opErr.Err == syscall.EADDRNOTAVAIL ||
  933. opErr.Err == syscall.EAGAIN ||
  934. opErr.Err == syscall.ENOMEM ||
  935. opErr.Err == syscall.EMFILE ||
  936. opErr.Err == syscall.ENFILE {
  937. log.WithTraceFields(
  938. LogFields{"error": opErr.Err}).Error(
  939. "port forward dial failed due to unavailable resource")
  940. }
  941. }
  942. }
  943. type sshClient struct {
  944. sync.Mutex
  945. sshServer *sshServer
  946. sshListener *sshListener
  947. tunnelProtocol string
  948. sshConn ssh.Conn
  949. activityConn *common.ActivityMonitoredConn
  950. throttledConn *common.ThrottledConn
  951. geoIPData GeoIPData
  952. sessionID string
  953. isFirstTunnelInSession bool
  954. supportsServerRequests bool
  955. handshakeState handshakeState
  956. udpChannel ssh.Channel
  957. packetTunnelChannel ssh.Channel
  958. trafficRules TrafficRules
  959. tcpTrafficState trafficState
  960. udpTrafficState trafficState
  961. qualityMetrics qualityMetrics
  962. tcpPortForwardLRU *common.LRUConns
  963. oslClientSeedState *osl.ClientSeedState
  964. signalIssueSLOKs chan struct{}
  965. runCtx context.Context
  966. stopRunning context.CancelFunc
  967. stopped chan struct{}
  968. tcpPortForwardDialingAvailableSignal context.CancelFunc
  969. releaseAuthorizations func()
  970. stopTimer *time.Timer
  971. preHandshakeRandomStreamMetrics randomStreamMetrics
  972. postHandshakeRandomStreamMetrics randomStreamMetrics
  973. sendAlertRequests chan protocol.AlertRequest
  974. sentAlertRequests map[protocol.AlertRequest]bool
  975. }
  976. type trafficState struct {
  977. bytesUp int64
  978. bytesDown int64
  979. concurrentDialingPortForwardCount int64
  980. peakConcurrentDialingPortForwardCount int64
  981. concurrentPortForwardCount int64
  982. peakConcurrentPortForwardCount int64
  983. totalPortForwardCount int64
  984. availablePortForwardCond *sync.Cond
  985. }
  986. type randomStreamMetrics struct {
  987. count int
  988. upstreamBytes int
  989. receivedUpstreamBytes int
  990. downstreamBytes int
  991. sentDownstreamBytes int
  992. }
  993. // qualityMetrics records upstream TCP dial attempts and
  994. // elapsed time. Elapsed time includes the full TCP handshake
  995. // and, in aggregate, is a measure of the quality of the
  996. // upstream link. These stats are recorded by each sshClient
  997. // and then reported and reset in sshServer.getLoadStats().
  998. type qualityMetrics struct {
  999. TCPPortForwardDialedCount int64
  1000. TCPPortForwardDialedDuration time.Duration
  1001. TCPPortForwardFailedCount int64
  1002. TCPPortForwardFailedDuration time.Duration
  1003. TCPPortForwardRejectedDialingLimitCount int64
  1004. TCPPortForwardRejectedDisallowedCount int64
  1005. UDPPortForwardRejectedDisallowedCount int64
  1006. TCPIPv4PortForwardDialedCount int64
  1007. TCPIPv4PortForwardDialedDuration time.Duration
  1008. TCPIPv4PortForwardFailedCount int64
  1009. TCPIPv4PortForwardFailedDuration time.Duration
  1010. TCPIPv6PortForwardDialedCount int64
  1011. TCPIPv6PortForwardDialedDuration time.Duration
  1012. TCPIPv6PortForwardFailedCount int64
  1013. TCPIPv6PortForwardFailedDuration time.Duration
  1014. }
  1015. type handshakeState struct {
  1016. completed bool
  1017. apiProtocol string
  1018. apiParams common.APIParameters
  1019. authorizedAccessTypes []string
  1020. authorizationsRevoked bool
  1021. expectDomainBytes bool
  1022. establishedTunnelsCount int
  1023. }
  1024. type handshakeStateInfo struct {
  1025. activeAuthorizationIDs []string
  1026. authorizedAccessTypes []string
  1027. upstreamBytesPerSecond int64
  1028. downstreamBytesPerSecond int64
  1029. }
  1030. func newSshClient(
  1031. sshServer *sshServer,
  1032. sshListener *sshListener,
  1033. tunnelProtocol string,
  1034. geoIPData GeoIPData) *sshClient {
  1035. runCtx, stopRunning := context.WithCancel(context.Background())
  1036. // isFirstTunnelInSession is defaulted to true so that the pre-handshake
  1037. // traffic rules won't apply UnthrottleFirstTunnelOnly and negate any
  1038. // unthrottled bytes during the initial protocol negotiation.
  1039. client := &sshClient{
  1040. sshServer: sshServer,
  1041. sshListener: sshListener,
  1042. tunnelProtocol: tunnelProtocol,
  1043. geoIPData: geoIPData,
  1044. isFirstTunnelInSession: true,
  1045. tcpPortForwardLRU: common.NewLRUConns(),
  1046. signalIssueSLOKs: make(chan struct{}, 1),
  1047. runCtx: runCtx,
  1048. stopRunning: stopRunning,
  1049. stopped: make(chan struct{}),
  1050. sendAlertRequests: make(chan protocol.AlertRequest, ALERT_REQUEST_QUEUE_BUFFER_SIZE),
  1051. sentAlertRequests: make(map[protocol.AlertRequest]bool),
  1052. }
  1053. client.tcpTrafficState.availablePortForwardCond = sync.NewCond(new(sync.Mutex))
  1054. client.udpTrafficState.availablePortForwardCond = sync.NewCond(new(sync.Mutex))
  1055. return client
  1056. }
  1057. func (sshClient *sshClient) run(
  1058. baseConn net.Conn, onSSHHandshakeFinished func()) {
  1059. // When run returns, the client has fully stopped, with all SSH state torn
  1060. // down and no port forwards or API requests in progress.
  1061. defer close(sshClient.stopped)
  1062. // onSSHHandshakeFinished must be called even if the SSH handshake is aborted.
  1063. defer func() {
  1064. if onSSHHandshakeFinished != nil {
  1065. onSSHHandshakeFinished()
  1066. }
  1067. }()
  1068. // Set initial traffic rules, pre-handshake, based on currently known info.
  1069. sshClient.setTrafficRules()
  1070. conn := baseConn
  1071. // Wrap the base client connection with an ActivityMonitoredConn which will
  1072. // terminate the connection if no data is received before the deadline. This
  1073. // timeout is in effect for the entire duration of the SSH connection. Clients
  1074. // must actively use the connection or send SSH keep alive requests to keep
  1075. // the connection active. Writes are not considered reliable activity indicators
  1076. // due to buffering.
  1077. activityConn, err := common.NewActivityMonitoredConn(
  1078. conn,
  1079. SSH_CONNECTION_READ_DEADLINE,
  1080. false,
  1081. nil,
  1082. nil)
  1083. if err != nil {
  1084. conn.Close()
  1085. if !isExpectedTunnelIOError(err) {
  1086. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  1087. }
  1088. return
  1089. }
  1090. conn = activityConn
  1091. // Further wrap the connection in a rate limiting ThrottledConn.
  1092. throttledConn := common.NewThrottledConn(conn, sshClient.rateLimits())
  1093. conn = throttledConn
  1094. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  1095. // respect shutdownBroadcast and implement a specific handshake timeout.
  1096. // The timeout is to reclaim network resources in case the handshake takes
  1097. // too long.
  1098. type sshNewServerConnResult struct {
  1099. obfuscatedSSHConn *obfuscator.ObfuscatedSSHConn
  1100. sshConn *ssh.ServerConn
  1101. channels <-chan ssh.NewChannel
  1102. requests <-chan *ssh.Request
  1103. err error
  1104. }
  1105. resultChannel := make(chan *sshNewServerConnResult, 2)
  1106. var afterFunc *time.Timer
  1107. if sshClient.sshServer.support.Config.sshHandshakeTimeout > 0 {
  1108. afterFunc = time.AfterFunc(sshClient.sshServer.support.Config.sshHandshakeTimeout, func() {
  1109. resultChannel <- &sshNewServerConnResult{err: std_errors.New("ssh handshake timeout")}
  1110. })
  1111. }
  1112. go func(baseConn, conn net.Conn) {
  1113. sshServerConfig := &ssh.ServerConfig{
  1114. PasswordCallback: sshClient.passwordCallback,
  1115. AuthLogCallback: sshClient.authLogCallback,
  1116. ServerVersion: sshClient.sshServer.support.Config.SSHServerVersion,
  1117. }
  1118. sshServerConfig.AddHostKey(sshClient.sshServer.sshHostKey)
  1119. var err error
  1120. if protocol.TunnelProtocolUsesObfuscatedSSH(sshClient.tunnelProtocol) {
  1121. // With Encrypt-then-MAC hash algorithms, packet length is
  1122. // transmitted in plaintext, which aids in traffic analysis;
  1123. // clients may still send Encrypt-then-MAC algorithms in their
  1124. // KEX_INIT message, but do not select these algorithms.
  1125. //
  1126. // The exception is TUNNEL_PROTOCOL_SSH, which is intended to appear
  1127. // like SSH on the wire.
  1128. sshServerConfig.NoEncryptThenMACHash = true
  1129. } else {
  1130. // For TUNNEL_PROTOCOL_SSH only, randomize KEX.
  1131. if sshClient.sshServer.support.Config.ObfuscatedSSHKey != "" {
  1132. sshServerConfig.KEXPRNGSeed, err = protocol.DeriveSSHServerKEXPRNGSeed(
  1133. sshClient.sshServer.support.Config.ObfuscatedSSHKey)
  1134. if err != nil {
  1135. err = errors.Trace(err)
  1136. }
  1137. }
  1138. }
  1139. result := &sshNewServerConnResult{}
  1140. // Wrap the connection in an SSH deobfuscator when required.
  1141. if err == nil && protocol.TunnelProtocolUsesObfuscatedSSH(sshClient.tunnelProtocol) {
  1142. // Note: NewServerObfuscatedSSHConn blocks on network I/O
  1143. // TODO: ensure this won't block shutdown
  1144. result.obfuscatedSSHConn, err = obfuscator.NewServerObfuscatedSSHConn(
  1145. conn,
  1146. sshClient.sshServer.support.Config.ObfuscatedSSHKey,
  1147. sshClient.sshServer.obfuscatorSeedHistory,
  1148. func(clientIP string, err error, logFields common.LogFields) {
  1149. logIrregularTunnel(
  1150. sshClient.sshServer.support,
  1151. sshClient.sshListener.tunnelProtocol,
  1152. sshClient.sshListener.port,
  1153. clientIP,
  1154. errors.Trace(err),
  1155. LogFields(logFields))
  1156. })
  1157. if err != nil {
  1158. err = errors.Trace(err)
  1159. } else {
  1160. conn = result.obfuscatedSSHConn
  1161. }
  1162. // Now seed fragmentor, when present, with seed derived from
  1163. // initial obfuscator message. See tactics.Listener.Accept.
  1164. // This must preceed ssh.NewServerConn to ensure fragmentor
  1165. // is seeded before downstream bytes are written.
  1166. if err == nil && sshClient.tunnelProtocol == protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH {
  1167. if fragmentorConn, ok := baseConn.(*fragmentor.Conn); ok {
  1168. var fragmentorPRNG *prng.PRNG
  1169. fragmentorPRNG, err = result.obfuscatedSSHConn.GetDerivedPRNG("server-side-fragmentor")
  1170. if err != nil {
  1171. err = errors.Trace(err)
  1172. } else {
  1173. fragmentorConn.SetPRNG(fragmentorPRNG)
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if err == nil {
  1179. result.sshConn, result.channels, result.requests, err =
  1180. ssh.NewServerConn(conn, sshServerConfig)
  1181. if err != nil {
  1182. err = errors.Trace(err)
  1183. }
  1184. }
  1185. result.err = err
  1186. resultChannel <- result
  1187. }(baseConn, conn)
  1188. var result *sshNewServerConnResult
  1189. select {
  1190. case result = <-resultChannel:
  1191. case <-sshClient.sshServer.shutdownBroadcast:
  1192. // Close() will interrupt an ongoing handshake
  1193. // TODO: wait for SSH handshake goroutines to exit before returning?
  1194. conn.Close()
  1195. return
  1196. }
  1197. if afterFunc != nil {
  1198. afterFunc.Stop()
  1199. }
  1200. if result.err != nil {
  1201. conn.Close()
  1202. // This is a Debug log due to noise. The handshake often fails due to I/O
  1203. // errors as clients frequently interrupt connections in progress when
  1204. // client-side load balancing completes a connection to a different server.
  1205. log.WithTraceFields(LogFields{"error": result.err}).Debug("handshake failed")
  1206. return
  1207. }
  1208. // The SSH handshake has finished successfully; notify now to allow other
  1209. // blocked SSH handshakes to proceed.
  1210. if onSSHHandshakeFinished != nil {
  1211. onSSHHandshakeFinished()
  1212. }
  1213. onSSHHandshakeFinished = nil
  1214. sshClient.Lock()
  1215. sshClient.sshConn = result.sshConn
  1216. sshClient.activityConn = activityConn
  1217. sshClient.throttledConn = throttledConn
  1218. sshClient.Unlock()
  1219. if !sshClient.sshServer.registerEstablishedClient(sshClient) {
  1220. conn.Close()
  1221. log.WithTrace().Warning("register failed")
  1222. return
  1223. }
  1224. sshClient.runTunnel(result.channels, result.requests)
  1225. // Note: sshServer.unregisterEstablishedClient calls sshClient.stop(),
  1226. // which also closes underlying transport Conn.
  1227. sshClient.sshServer.unregisterEstablishedClient(sshClient)
  1228. // Some conns report additional metrics. Meek conns report resiliency
  1229. // metrics and fragmentor.Conns report fragmentor configs.
  1230. //
  1231. // Limitation: for meek, GetMetrics from underlying fragmentor.Conn(s)
  1232. // should be called in order to log fragmentor metrics for meek sessions.
  1233. var additionalMetrics []LogFields
  1234. if metricsSource, ok := baseConn.(common.MetricsSource); ok {
  1235. additionalMetrics = append(
  1236. additionalMetrics, LogFields(metricsSource.GetMetrics()))
  1237. }
  1238. if result.obfuscatedSSHConn != nil {
  1239. additionalMetrics = append(
  1240. additionalMetrics, LogFields(result.obfuscatedSSHConn.GetMetrics()))
  1241. }
  1242. sshClient.logTunnel(additionalMetrics)
  1243. // Transfer OSL seed state -- the OSL progress -- from the closing
  1244. // client to the session cache so the client can resume its progress
  1245. // if it reconnects to this same server.
  1246. // Note: following setOSLConfig order of locking.
  1247. sshClient.Lock()
  1248. if sshClient.oslClientSeedState != nil {
  1249. sshClient.sshServer.oslSessionCacheMutex.Lock()
  1250. sshClient.oslClientSeedState.Hibernate()
  1251. sshClient.sshServer.oslSessionCache.Set(
  1252. sshClient.sessionID, sshClient.oslClientSeedState, cache.DefaultExpiration)
  1253. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  1254. sshClient.oslClientSeedState = nil
  1255. }
  1256. sshClient.Unlock()
  1257. // Initiate cleanup of the GeoIP session cache. To allow for post-tunnel
  1258. // final status requests, the lifetime of cached GeoIP records exceeds the
  1259. // lifetime of the sshClient.
  1260. sshClient.sshServer.support.GeoIPService.MarkSessionCacheToExpire(sshClient.sessionID)
  1261. }
  1262. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  1263. expectedSessionIDLength := 2 * protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
  1264. expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH
  1265. var sshPasswordPayload protocol.SSHPasswordPayload
  1266. err := json.Unmarshal(password, &sshPasswordPayload)
  1267. if err != nil {
  1268. // Backwards compatibility case: instead of a JSON payload, older clients
  1269. // send the hex encoded session ID prepended to the SSH password.
  1270. // Note: there's an even older case where clients don't send any session ID,
  1271. // but that's no longer supported.
  1272. if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
  1273. sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
  1274. sshPasswordPayload.SshPassword = string(password[expectedSessionIDLength:])
  1275. } else {
  1276. return nil, errors.Tracef("invalid password payload for %q", conn.User())
  1277. }
  1278. }
  1279. if !isHexDigits(sshClient.sshServer.support.Config, sshPasswordPayload.SessionId) ||
  1280. len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
  1281. return nil, errors.Tracef("invalid session ID for %q", conn.User())
  1282. }
  1283. userOk := (subtle.ConstantTimeCompare(
  1284. []byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
  1285. passwordOk := (subtle.ConstantTimeCompare(
  1286. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
  1287. if !userOk || !passwordOk {
  1288. return nil, errors.Tracef("invalid password for %q", conn.User())
  1289. }
  1290. sessionID := sshPasswordPayload.SessionId
  1291. // The GeoIP session cache will be populated if there was a previous tunnel
  1292. // with this session ID. This will be true up to GEOIP_SESSION_CACHE_TTL, which
  1293. // is currently much longer than the OSL session cache, another option to use if
  1294. // the GeoIP session cache is retired (the GeoIP session cache currently only
  1295. // supports legacy use cases).
  1296. isFirstTunnelInSession := !sshClient.sshServer.support.GeoIPService.InSessionCache(sessionID)
  1297. supportsServerRequests := common.Contains(
  1298. sshPasswordPayload.ClientCapabilities, protocol.CLIENT_CAPABILITY_SERVER_REQUESTS)
  1299. sshClient.Lock()
  1300. // After this point, these values are read-only as they are read
  1301. // without obtaining sshClient.Lock.
  1302. sshClient.sessionID = sessionID
  1303. sshClient.isFirstTunnelInSession = isFirstTunnelInSession
  1304. sshClient.supportsServerRequests = supportsServerRequests
  1305. geoIPData := sshClient.geoIPData
  1306. sshClient.Unlock()
  1307. // Store the GeoIP data associated with the session ID. This makes
  1308. // the GeoIP data available to the web server for web API requests.
  1309. // A cache that's distinct from the sshClient record is used to allow
  1310. // for or post-tunnel final status requests.
  1311. // If the client is reconnecting with the same session ID, this call
  1312. // will undo the expiry set by MarkSessionCacheToExpire.
  1313. sshClient.sshServer.support.GeoIPService.SetSessionCache(sessionID, geoIPData)
  1314. return nil, nil
  1315. }
  1316. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  1317. if err != nil {
  1318. if method == "none" && err.Error() == "no auth passed yet" {
  1319. // In this case, the callback invocation is noise from auth negotiation
  1320. return
  1321. }
  1322. // Note: here we previously logged messages for fail2ban to act on. This is no longer
  1323. // done as the complexity outweighs the benefits.
  1324. //
  1325. // - The SSH credential is not secret -- it's in the server entry. Attackers targeting
  1326. // the server likely already have the credential. On the other hand, random scanning and
  1327. // brute forcing is mitigated with high entropy random passwords, rate limiting
  1328. // (implemented on the host via iptables), and limited capabilities (the SSH session can
  1329. // only port forward).
  1330. //
  1331. // - fail2ban coverage was inconsistent; in the case of an unfronted meek protocol through
  1332. // an upstream proxy, the remote address is the upstream proxy, which should not be blocked.
  1333. // The X-Forwarded-For header cant be used instead as it may be forged and used to get IPs
  1334. // deliberately blocked; and in any case fail2ban adds iptables rules which can only block
  1335. // by direct remote IP, not by original client IP. Fronted meek has the same iptables issue.
  1336. //
  1337. // Random scanning and brute forcing of port 22 will result in log noise. To mitigate this,
  1338. // not every authentication failure is logged. A summary log is emitted periodically to
  1339. // retain some record of this activity in case this is relevant to, e.g., a performance
  1340. // investigation.
  1341. atomic.AddInt64(&sshClient.sshServer.authFailedCount, 1)
  1342. lastAuthLog := monotime.Time(atomic.LoadInt64(&sshClient.sshServer.lastAuthLog))
  1343. if monotime.Since(lastAuthLog) > SSH_AUTH_LOG_PERIOD {
  1344. now := int64(monotime.Now())
  1345. if atomic.CompareAndSwapInt64(&sshClient.sshServer.lastAuthLog, int64(lastAuthLog), now) {
  1346. count := atomic.SwapInt64(&sshClient.sshServer.authFailedCount, 0)
  1347. log.WithTraceFields(
  1348. LogFields{"lastError": err, "failedCount": count}).Warning("authentication failures")
  1349. }
  1350. }
  1351. log.WithTraceFields(LogFields{"error": err, "method": method}).Debug("authentication failed")
  1352. } else {
  1353. log.WithTraceFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  1354. }
  1355. }
  1356. // stop signals the ssh connection to shutdown. After sshConn.Wait returns,
  1357. // the SSH connection has terminated but sshClient.run may still be running and
  1358. // in the process of exiting.
  1359. //
  1360. // The shutdown process must complete rapidly and not, e.g., block on network
  1361. // I/O, as newly connecting clients need to await stop completion of any
  1362. // existing connection that shares the same session ID.
  1363. func (sshClient *sshClient) stop() {
  1364. sshClient.sshConn.Close()
  1365. sshClient.sshConn.Wait()
  1366. }
  1367. // awaitStopped will block until sshClient.run has exited, at which point all
  1368. // worker goroutines associated with the sshClient, including any in-flight
  1369. // API handlers, will have exited.
  1370. func (sshClient *sshClient) awaitStopped() {
  1371. <-sshClient.stopped
  1372. }
  1373. // runTunnel handles/dispatches new channels and new requests from the client.
  1374. // When the SSH client connection closes, both the channels and requests channels
  1375. // will close and runTunnel will exit.
  1376. func (sshClient *sshClient) runTunnel(
  1377. channels <-chan ssh.NewChannel,
  1378. requests <-chan *ssh.Request) {
  1379. waitGroup := new(sync.WaitGroup)
  1380. // Start client SSH API request handler
  1381. waitGroup.Add(1)
  1382. go func() {
  1383. defer waitGroup.Done()
  1384. sshClient.handleSSHRequests(requests)
  1385. }()
  1386. // Start request senders
  1387. if sshClient.supportsServerRequests {
  1388. waitGroup.Add(1)
  1389. go func() {
  1390. defer waitGroup.Done()
  1391. sshClient.runOSLSender()
  1392. }()
  1393. waitGroup.Add(1)
  1394. go func() {
  1395. defer waitGroup.Done()
  1396. sshClient.runAlertSender()
  1397. }()
  1398. }
  1399. // Start the TCP port forward manager
  1400. // The queue size is set to the traffic rules (MaxTCPPortForwardCount +
  1401. // MaxTCPDialingPortForwardCount), which is a reasonable indication of resource
  1402. // limits per client; when that value is not set, a default is used.
  1403. // A limitation: this queue size is set once and doesn't change, for this client,
  1404. // when traffic rules are reloaded.
  1405. queueSize := sshClient.getTCPPortForwardQueueSize()
  1406. if queueSize == 0 {
  1407. queueSize = SSH_TCP_PORT_FORWARD_QUEUE_SIZE
  1408. }
  1409. newTCPPortForwards := make(chan *newTCPPortForward, queueSize)
  1410. waitGroup.Add(1)
  1411. go func() {
  1412. defer waitGroup.Done()
  1413. sshClient.handleTCPPortForwards(waitGroup, newTCPPortForwards)
  1414. }()
  1415. // Handle new channel (port forward) requests from the client.
  1416. for newChannel := range channels {
  1417. switch newChannel.ChannelType() {
  1418. case protocol.RANDOM_STREAM_CHANNEL_TYPE:
  1419. sshClient.handleNewRandomStreamChannel(waitGroup, newChannel)
  1420. case protocol.PACKET_TUNNEL_CHANNEL_TYPE:
  1421. sshClient.handleNewPacketTunnelChannel(waitGroup, newChannel)
  1422. case "direct-tcpip":
  1423. sshClient.handleNewTCPPortForwardChannel(waitGroup, newChannel, newTCPPortForwards)
  1424. default:
  1425. sshClient.rejectNewChannel(newChannel,
  1426. fmt.Sprintf("unknown or unsupported channel type: %s", newChannel.ChannelType()))
  1427. }
  1428. }
  1429. // The channel loop is interrupted by a client
  1430. // disconnect or by calling sshClient.stop().
  1431. // Stop the TCP port forward manager
  1432. close(newTCPPortForwards)
  1433. // Stop all other worker goroutines
  1434. sshClient.stopRunning()
  1435. if sshClient.sshServer.support.Config.RunPacketTunnel {
  1436. // PacketTunnelServer.ClientDisconnected stops packet tunnel workers.
  1437. sshClient.sshServer.support.PacketTunnelServer.ClientDisconnected(
  1438. sshClient.sessionID)
  1439. }
  1440. waitGroup.Wait()
  1441. sshClient.cleanupAuthorizations()
  1442. }
  1443. func (sshClient *sshClient) handleSSHRequests(requests <-chan *ssh.Request) {
  1444. for request := range requests {
  1445. // Requests are processed serially; API responses must be sent in request order.
  1446. var responsePayload []byte
  1447. var err error
  1448. if request.Type == "keepalive@openssh.com" {
  1449. // SSH keep alive round trips are used as speed test samples.
  1450. responsePayload, err = tactics.MakeSpeedTestResponse(
  1451. SSH_KEEP_ALIVE_PAYLOAD_MIN_BYTES, SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES)
  1452. } else {
  1453. // All other requests are assumed to be API requests.
  1454. sshClient.Lock()
  1455. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  1456. sshClient.Unlock()
  1457. // Note: unlock before use is only safe as long as referenced sshClient data,
  1458. // such as slices in handshakeState, is read-only after initially set.
  1459. responsePayload, err = sshAPIRequestHandler(
  1460. sshClient.sshServer.support,
  1461. sshClient.geoIPData,
  1462. authorizedAccessTypes,
  1463. request.Type,
  1464. request.Payload)
  1465. }
  1466. if err == nil {
  1467. err = request.Reply(true, responsePayload)
  1468. } else {
  1469. log.WithTraceFields(LogFields{"error": err}).Warning("request failed")
  1470. err = request.Reply(false, nil)
  1471. }
  1472. if err != nil {
  1473. if !isExpectedTunnelIOError(err) {
  1474. log.WithTraceFields(LogFields{"error": err}).Warning("response failed")
  1475. }
  1476. }
  1477. }
  1478. }
  1479. type newTCPPortForward struct {
  1480. enqueueTime time.Time
  1481. hostToConnect string
  1482. portToConnect int
  1483. newChannel ssh.NewChannel
  1484. }
  1485. func (sshClient *sshClient) handleTCPPortForwards(
  1486. waitGroup *sync.WaitGroup,
  1487. newTCPPortForwards chan *newTCPPortForward) {
  1488. // Lifecycle of a TCP port forward:
  1489. //
  1490. // 1. A "direct-tcpip" SSH request is received from the client.
  1491. //
  1492. // A new TCP port forward request is enqueued. The queue delivers TCP port
  1493. // forward requests to the TCP port forward manager, which enforces the TCP
  1494. // port forward dial limit.
  1495. //
  1496. // Enqueuing new requests allows for reading further SSH requests from the
  1497. // client without blocking when the dial limit is hit; this is to permit new
  1498. // UDP/udpgw port forwards to be restablished without delay. The maximum size
  1499. // of the queue enforces a hard cap on resources consumed by a client in the
  1500. // pre-dial phase. When the queue is full, new TCP port forwards are
  1501. // immediately rejected.
  1502. //
  1503. // 2. The TCP port forward manager dequeues the request.
  1504. //
  1505. // The manager calls dialingTCPPortForward(), which increments
  1506. // concurrentDialingPortForwardCount, and calls
  1507. // isTCPDialingPortForwardLimitExceeded() to check the concurrent dialing
  1508. // count.
  1509. //
  1510. // The manager enforces the concurrent TCP dial limit: when at the limit, the
  1511. // manager blocks waiting for the number of dials to drop below the limit before
  1512. // dispatching the request to handleTCPPortForward(), which will run in its own
  1513. // goroutine and will dial and relay the port forward.
  1514. //
  1515. // The block delays the current request and also halts dequeuing of subsequent
  1516. // requests and could ultimately cause requests to be immediately rejected if
  1517. // the queue fills. These actions are intended to apply back pressure when
  1518. // upstream network resources are impaired.
  1519. //
  1520. // The time spent in the queue is deducted from the port forward's dial timeout.
  1521. // The time spent blocking while at the dial limit is similarly deducted from
  1522. // the dial timeout. If the dial timeout has expired before the dial begins, the
  1523. // port forward is rejected and a stat is recorded.
  1524. //
  1525. // 3. handleTCPPortForward() performs the port forward dial and relaying.
  1526. //
  1527. // a. Dial the target, using the dial timeout remaining after queue and blocking
  1528. // time is deducted.
  1529. //
  1530. // b. If the dial fails, call abortedTCPPortForward() to decrement
  1531. // concurrentDialingPortForwardCount, freeing up a dial slot.
  1532. //
  1533. // c. If the dial succeeds, call establishedPortForward(), which decrements
  1534. // concurrentDialingPortForwardCount and increments concurrentPortForwardCount,
  1535. // the "established" port forward count.
  1536. //
  1537. // d. Check isPortForwardLimitExceeded(), which enforces the configurable limit on
  1538. // concurrentPortForwardCount, the number of _established_ TCP port forwards.
  1539. // If the limit is exceeded, the LRU established TCP port forward is closed and
  1540. // the newly established TCP port forward proceeds. This LRU logic allows some
  1541. // dangling resource consumption (e.g., TIME_WAIT) while providing a better
  1542. // experience for clients.
  1543. //
  1544. // e. Relay data.
  1545. //
  1546. // f. Call closedPortForward() which decrements concurrentPortForwardCount and
  1547. // records bytes transferred.
  1548. for newPortForward := range newTCPPortForwards {
  1549. remainingDialTimeout :=
  1550. time.Duration(sshClient.getDialTCPPortForwardTimeoutMilliseconds())*time.Millisecond -
  1551. time.Since(newPortForward.enqueueTime)
  1552. if remainingDialTimeout <= 0 {
  1553. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  1554. sshClient.rejectNewChannel(
  1555. newPortForward.newChannel, "TCP port forward timed out in queue")
  1556. continue
  1557. }
  1558. // Reserve a TCP dialing slot.
  1559. //
  1560. // TOCTOU note: important to increment counts _before_ checking limits; otherwise,
  1561. // the client could potentially consume excess resources by initiating many port
  1562. // forwards concurrently.
  1563. sshClient.dialingTCPPortForward()
  1564. // When max dials are in progress, wait up to remainingDialTimeout for dialing
  1565. // to become available. This blocks all dequeing.
  1566. if sshClient.isTCPDialingPortForwardLimitExceeded() {
  1567. blockStartTime := time.Now()
  1568. ctx, cancelCtx := context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  1569. sshClient.setTCPPortForwardDialingAvailableSignal(cancelCtx)
  1570. <-ctx.Done()
  1571. sshClient.setTCPPortForwardDialingAvailableSignal(nil)
  1572. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  1573. remainingDialTimeout -= time.Since(blockStartTime)
  1574. }
  1575. if remainingDialTimeout <= 0 {
  1576. // Release the dialing slot here since handleTCPChannel() won't be called.
  1577. sshClient.abortedTCPPortForward()
  1578. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  1579. sshClient.rejectNewChannel(
  1580. newPortForward.newChannel, "TCP port forward timed out before dialing")
  1581. continue
  1582. }
  1583. // Dial and relay the TCP port forward. handleTCPChannel is run in its own worker goroutine.
  1584. // handleTCPChannel will release the dialing slot reserved by dialingTCPPortForward(); and
  1585. // will deal with remainingDialTimeout <= 0.
  1586. waitGroup.Add(1)
  1587. go func(remainingDialTimeout time.Duration, newPortForward *newTCPPortForward) {
  1588. defer waitGroup.Done()
  1589. sshClient.handleTCPChannel(
  1590. remainingDialTimeout,
  1591. newPortForward.hostToConnect,
  1592. newPortForward.portToConnect,
  1593. newPortForward.newChannel)
  1594. }(remainingDialTimeout, newPortForward)
  1595. }
  1596. }
  1597. func (sshClient *sshClient) handleNewRandomStreamChannel(
  1598. waitGroup *sync.WaitGroup, newChannel ssh.NewChannel) {
  1599. // A random stream channel returns the requested number of bytes -- random
  1600. // bytes -- to the client while also consuming and discarding bytes sent
  1601. // by the client.
  1602. //
  1603. // One use case for the random stream channel is a liveness test that the
  1604. // client performs to confirm that the tunnel is live. As the liveness
  1605. // test is performed in the concurrent establishment phase, before
  1606. // selecting a single candidate for handshake, the random stream channel
  1607. // is available pre-handshake, albeit with additional restrictions.
  1608. //
  1609. // The random stream is subject to throttling in traffic rules; for
  1610. // unthrottled liveness tests, set initial Read/WriteUnthrottledBytes as
  1611. // required. The random stream maximum count and response size cap
  1612. // mitigate clients abusing the facility to waste server resources.
  1613. //
  1614. // Like all other channels, this channel type is handled asynchronously,
  1615. // so it's possible to run at any point in the tunnel lifecycle.
  1616. //
  1617. // Up/downstream byte counts don't include SSH packet and request
  1618. // marshalling overhead.
  1619. var request protocol.RandomStreamRequest
  1620. err := json.Unmarshal(newChannel.ExtraData(), &request)
  1621. if err != nil {
  1622. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("invalid request: %s", err))
  1623. return
  1624. }
  1625. if request.UpstreamBytes > RANDOM_STREAM_MAX_BYTES {
  1626. sshClient.rejectNewChannel(newChannel,
  1627. fmt.Sprintf("invalid upstream bytes: %d", request.UpstreamBytes))
  1628. return
  1629. }
  1630. if request.DownstreamBytes > RANDOM_STREAM_MAX_BYTES {
  1631. sshClient.rejectNewChannel(newChannel,
  1632. fmt.Sprintf("invalid downstream bytes: %d", request.DownstreamBytes))
  1633. return
  1634. }
  1635. var metrics *randomStreamMetrics
  1636. sshClient.Lock()
  1637. if !sshClient.handshakeState.completed {
  1638. metrics = &sshClient.preHandshakeRandomStreamMetrics
  1639. } else {
  1640. metrics = &sshClient.postHandshakeRandomStreamMetrics
  1641. }
  1642. countOk := true
  1643. if !sshClient.handshakeState.completed &&
  1644. metrics.count >= PRE_HANDSHAKE_RANDOM_STREAM_MAX_COUNT {
  1645. countOk = false
  1646. } else {
  1647. metrics.count++
  1648. }
  1649. sshClient.Unlock()
  1650. if !countOk {
  1651. sshClient.rejectNewChannel(newChannel, "max count exceeded")
  1652. return
  1653. }
  1654. channel, requests, err := newChannel.Accept()
  1655. if err != nil {
  1656. if !isExpectedTunnelIOError(err) {
  1657. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  1658. }
  1659. return
  1660. }
  1661. go ssh.DiscardRequests(requests)
  1662. waitGroup.Add(1)
  1663. go func() {
  1664. defer waitGroup.Done()
  1665. received := 0
  1666. sent := 0
  1667. if request.UpstreamBytes > 0 {
  1668. n, err := io.CopyN(ioutil.Discard, channel, int64(request.UpstreamBytes))
  1669. received = int(n)
  1670. if err != nil {
  1671. if !isExpectedTunnelIOError(err) {
  1672. log.WithTraceFields(LogFields{"error": err}).Warning("receive failed")
  1673. }
  1674. // Fall through and record any bytes received...
  1675. }
  1676. }
  1677. if request.DownstreamBytes > 0 {
  1678. n, err := io.CopyN(channel, rand.Reader, int64(request.DownstreamBytes))
  1679. sent = int(n)
  1680. if err != nil {
  1681. if !isExpectedTunnelIOError(err) {
  1682. log.WithTraceFields(LogFields{"error": err}).Warning("send failed")
  1683. }
  1684. }
  1685. }
  1686. sshClient.Lock()
  1687. metrics.upstreamBytes += request.UpstreamBytes
  1688. metrics.receivedUpstreamBytes += received
  1689. metrics.downstreamBytes += request.DownstreamBytes
  1690. metrics.sentDownstreamBytes += sent
  1691. sshClient.Unlock()
  1692. channel.Close()
  1693. }()
  1694. }
  1695. func (sshClient *sshClient) handleNewPacketTunnelChannel(
  1696. waitGroup *sync.WaitGroup, newChannel ssh.NewChannel) {
  1697. // packet tunnel channels are handled by the packet tunnel server
  1698. // component. Each client may have at most one packet tunnel channel.
  1699. if !sshClient.sshServer.support.Config.RunPacketTunnel {
  1700. sshClient.rejectNewChannel(newChannel, "unsupported packet tunnel channel type")
  1701. return
  1702. }
  1703. // Accept this channel immediately. This channel will replace any
  1704. // previously existing packet tunnel channel for this client.
  1705. packetTunnelChannel, requests, err := newChannel.Accept()
  1706. if err != nil {
  1707. if !isExpectedTunnelIOError(err) {
  1708. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  1709. }
  1710. return
  1711. }
  1712. go ssh.DiscardRequests(requests)
  1713. sshClient.setPacketTunnelChannel(packetTunnelChannel)
  1714. // PacketTunnelServer will run the client's packet tunnel. If necessary, ClientConnected
  1715. // will stop packet tunnel workers for any previous packet tunnel channel.
  1716. checkAllowedTCPPortFunc := func(upstreamIPAddress net.IP, port int) bool {
  1717. return sshClient.isPortForwardPermitted(portForwardTypeTCP, upstreamIPAddress, port)
  1718. }
  1719. checkAllowedUDPPortFunc := func(upstreamIPAddress net.IP, port int) bool {
  1720. return sshClient.isPortForwardPermitted(portForwardTypeUDP, upstreamIPAddress, port)
  1721. }
  1722. flowActivityUpdaterMaker := func(
  1723. upstreamHostname string, upstreamIPAddress net.IP) []tun.FlowActivityUpdater {
  1724. var updaters []tun.FlowActivityUpdater
  1725. oslUpdater := sshClient.newClientSeedPortForward(upstreamIPAddress)
  1726. if oslUpdater != nil {
  1727. updaters = append(updaters, oslUpdater)
  1728. }
  1729. return updaters
  1730. }
  1731. metricUpdater := func(
  1732. TCPApplicationBytesDown, TCPApplicationBytesUp,
  1733. UDPApplicationBytesDown, UDPApplicationBytesUp int64) {
  1734. sshClient.Lock()
  1735. sshClient.tcpTrafficState.bytesDown += TCPApplicationBytesDown
  1736. sshClient.tcpTrafficState.bytesUp += TCPApplicationBytesUp
  1737. sshClient.udpTrafficState.bytesDown += UDPApplicationBytesDown
  1738. sshClient.udpTrafficState.bytesUp += UDPApplicationBytesUp
  1739. sshClient.Unlock()
  1740. }
  1741. err = sshClient.sshServer.support.PacketTunnelServer.ClientConnected(
  1742. sshClient.sessionID,
  1743. packetTunnelChannel,
  1744. checkAllowedTCPPortFunc,
  1745. checkAllowedUDPPortFunc,
  1746. flowActivityUpdaterMaker,
  1747. metricUpdater)
  1748. if err != nil {
  1749. log.WithTraceFields(LogFields{"error": err}).Warning("start packet tunnel client failed")
  1750. sshClient.setPacketTunnelChannel(nil)
  1751. }
  1752. }
  1753. func (sshClient *sshClient) handleNewTCPPortForwardChannel(
  1754. waitGroup *sync.WaitGroup, newChannel ssh.NewChannel,
  1755. newTCPPortForwards chan *newTCPPortForward) {
  1756. // udpgw client connections are dispatched immediately (clients use this for
  1757. // DNS, so it's essential to not block; and only one udpgw connection is
  1758. // retained at a time).
  1759. //
  1760. // All other TCP port forwards are dispatched via the TCP port forward
  1761. // manager queue.
  1762. // http://tools.ietf.org/html/rfc4254#section-7.2
  1763. var directTcpipExtraData struct {
  1764. HostToConnect string
  1765. PortToConnect uint32
  1766. OriginatorIPAddress string
  1767. OriginatorPort uint32
  1768. }
  1769. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  1770. if err != nil {
  1771. sshClient.rejectNewChannel(newChannel, "invalid extra data")
  1772. return
  1773. }
  1774. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  1775. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  1776. isUDPChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
  1777. sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
  1778. net.JoinHostPort(directTcpipExtraData.HostToConnect, strconv.Itoa(int(directTcpipExtraData.PortToConnect)))
  1779. if isUDPChannel {
  1780. // Dispatch immediately. handleUDPChannel runs the udpgw protocol in its
  1781. // own worker goroutine.
  1782. waitGroup.Add(1)
  1783. go func(channel ssh.NewChannel) {
  1784. defer waitGroup.Done()
  1785. sshClient.handleUDPChannel(channel)
  1786. }(newChannel)
  1787. } else {
  1788. // Dispatch via TCP port forward manager. When the queue is full, the channel
  1789. // is immediately rejected.
  1790. tcpPortForward := &newTCPPortForward{
  1791. enqueueTime: time.Now(),
  1792. hostToConnect: directTcpipExtraData.HostToConnect,
  1793. portToConnect: int(directTcpipExtraData.PortToConnect),
  1794. newChannel: newChannel,
  1795. }
  1796. select {
  1797. case newTCPPortForwards <- tcpPortForward:
  1798. default:
  1799. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  1800. sshClient.rejectNewChannel(newChannel, "TCP port forward dial queue full")
  1801. }
  1802. }
  1803. }
  1804. func (sshClient *sshClient) cleanupAuthorizations() {
  1805. sshClient.Lock()
  1806. if sshClient.releaseAuthorizations != nil {
  1807. sshClient.releaseAuthorizations()
  1808. }
  1809. if sshClient.stopTimer != nil {
  1810. sshClient.stopTimer.Stop()
  1811. }
  1812. sshClient.Unlock()
  1813. }
  1814. // setPacketTunnelChannel sets the single packet tunnel channel
  1815. // for this sshClient. Any existing packet tunnel channel is
  1816. // closed.
  1817. func (sshClient *sshClient) setPacketTunnelChannel(channel ssh.Channel) {
  1818. sshClient.Lock()
  1819. if sshClient.packetTunnelChannel != nil {
  1820. sshClient.packetTunnelChannel.Close()
  1821. }
  1822. sshClient.packetTunnelChannel = channel
  1823. sshClient.Unlock()
  1824. }
  1825. // setUDPChannel sets the single UDP channel for this sshClient.
  1826. // Each sshClient may have only one concurrent UDP channel. Each
  1827. // UDP channel multiplexes many UDP port forwards via the udpgw
  1828. // protocol. Any existing UDP channel is closed.
  1829. func (sshClient *sshClient) setUDPChannel(channel ssh.Channel) {
  1830. sshClient.Lock()
  1831. if sshClient.udpChannel != nil {
  1832. sshClient.udpChannel.Close()
  1833. }
  1834. sshClient.udpChannel = channel
  1835. sshClient.Unlock()
  1836. }
  1837. var serverTunnelStatParams = append(
  1838. []requestParamSpec{
  1839. {"last_connected", isLastConnected, requestParamOptional},
  1840. {"establishment_duration", isIntString, requestParamOptional}},
  1841. baseRequestParams...)
  1842. func (sshClient *sshClient) logTunnel(additionalMetrics []LogFields) {
  1843. // Note: reporting duration based on last confirmed data transfer, which
  1844. // is reads for sshClient.activityConn.GetActiveDuration(), and not
  1845. // connection closing is important for protocols such as meek. For
  1846. // meek, the connection remains open until the HTTP session expires,
  1847. // which may be some time after the tunnel has closed. (The meek
  1848. // protocol has no allowance for signalling payload EOF, and even if
  1849. // it did the client may not have the opportunity to send a final
  1850. // request with an EOF flag set.)
  1851. sshClient.Lock()
  1852. logFields := getRequestLogFields(
  1853. "server_tunnel",
  1854. sshClient.geoIPData,
  1855. sshClient.handshakeState.authorizedAccessTypes,
  1856. sshClient.handshakeState.apiParams,
  1857. serverTunnelStatParams)
  1858. // "relay_protocol" is sent with handshake API parameters. In pre-
  1859. // handshake logTunnel cases, this value is not yet known. As
  1860. // sshClient.tunnelProtocol is authoritative, set this value
  1861. // unconditionally, overwriting any value from handshake.
  1862. logFields["relay_protocol"] = sshClient.tunnelProtocol
  1863. if sshClient.sshListener.BPFProgramName != "" {
  1864. logFields["server_bpf"] = sshClient.sshListener.BPFProgramName
  1865. }
  1866. logFields["session_id"] = sshClient.sessionID
  1867. logFields["handshake_completed"] = sshClient.handshakeState.completed
  1868. logFields["start_time"] = sshClient.activityConn.GetStartTime()
  1869. logFields["duration"] = int64(sshClient.activityConn.GetActiveDuration() / time.Millisecond)
  1870. logFields["bytes_up_tcp"] = sshClient.tcpTrafficState.bytesUp
  1871. logFields["bytes_down_tcp"] = sshClient.tcpTrafficState.bytesDown
  1872. logFields["peak_concurrent_dialing_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentDialingPortForwardCount
  1873. logFields["peak_concurrent_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentPortForwardCount
  1874. logFields["total_port_forward_count_tcp"] = sshClient.tcpTrafficState.totalPortForwardCount
  1875. logFields["bytes_up_udp"] = sshClient.udpTrafficState.bytesUp
  1876. logFields["bytes_down_udp"] = sshClient.udpTrafficState.bytesDown
  1877. // sshClient.udpTrafficState.peakConcurrentDialingPortForwardCount isn't meaningful
  1878. logFields["peak_concurrent_port_forward_count_udp"] = sshClient.udpTrafficState.peakConcurrentPortForwardCount
  1879. logFields["total_port_forward_count_udp"] = sshClient.udpTrafficState.totalPortForwardCount
  1880. logFields["pre_handshake_random_stream_count"] = sshClient.preHandshakeRandomStreamMetrics.count
  1881. logFields["pre_handshake_random_stream_upstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.upstreamBytes
  1882. logFields["pre_handshake_random_stream_received_upstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.receivedUpstreamBytes
  1883. logFields["pre_handshake_random_stream_downstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.downstreamBytes
  1884. logFields["pre_handshake_random_stream_sent_downstream_bytes"] = sshClient.preHandshakeRandomStreamMetrics.sentDownstreamBytes
  1885. logFields["random_stream_count"] = sshClient.postHandshakeRandomStreamMetrics.count
  1886. logFields["random_stream_upstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.upstreamBytes
  1887. logFields["random_stream_received_upstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.receivedUpstreamBytes
  1888. logFields["random_stream_downstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.downstreamBytes
  1889. logFields["random_stream_sent_downstream_bytes"] = sshClient.postHandshakeRandomStreamMetrics.sentDownstreamBytes
  1890. // Pre-calculate a total-tunneled-bytes field. This total is used
  1891. // extensively in analytics and is more performant when pre-calculated.
  1892. logFields["bytes"] = sshClient.tcpTrafficState.bytesUp +
  1893. sshClient.tcpTrafficState.bytesDown +
  1894. sshClient.udpTrafficState.bytesUp +
  1895. sshClient.udpTrafficState.bytesDown
  1896. // Merge in additional metrics from the optional metrics source
  1897. for _, metrics := range additionalMetrics {
  1898. for name, value := range metrics {
  1899. // Don't overwrite any basic fields
  1900. if logFields[name] == nil {
  1901. logFields[name] = value
  1902. }
  1903. }
  1904. }
  1905. sshClient.Unlock()
  1906. // Note: unlock before use is only safe as long as referenced sshClient data,
  1907. // such as slices in handshakeState, is read-only after initially set.
  1908. log.LogRawFieldsWithTimestamp(logFields)
  1909. }
  1910. var blocklistHitsStatParams = []requestParamSpec{
  1911. {"propagation_channel_id", isHexDigits, 0},
  1912. {"sponsor_id", isHexDigits, 0},
  1913. {"client_version", isIntString, requestParamLogStringAsInt},
  1914. {"client_platform", isClientPlatform, 0},
  1915. {"client_build_rev", isHexDigits, requestParamOptional},
  1916. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1917. {"device_region", isAnyString, requestParamOptional},
  1918. {"egress_region", isRegionCode, requestParamOptional},
  1919. {"session_id", isHexDigits, 0},
  1920. {"last_connected", isLastConnected, requestParamOptional},
  1921. }
  1922. func (sshClient *sshClient) logBlocklistHits(IP net.IP, domain string, tags []BlocklistTag) {
  1923. sshClient.Lock()
  1924. logFields := getRequestLogFields(
  1925. "server_blocklist_hit",
  1926. sshClient.geoIPData,
  1927. sshClient.handshakeState.authorizedAccessTypes,
  1928. sshClient.handshakeState.apiParams,
  1929. blocklistHitsStatParams)
  1930. logFields["session_id"] = sshClient.sessionID
  1931. // Note: see comment in logTunnel regarding unlock and concurrent access.
  1932. sshClient.Unlock()
  1933. for _, tag := range tags {
  1934. if IP != nil {
  1935. logFields["blocklist_ip_address"] = IP.String()
  1936. }
  1937. if domain != "" {
  1938. logFields["blocklist_domain"] = domain
  1939. }
  1940. logFields["blocklist_source"] = tag.Source
  1941. logFields["blocklist_subject"] = tag.Subject
  1942. log.LogRawFieldsWithTimestamp(logFields)
  1943. }
  1944. }
  1945. func (sshClient *sshClient) runOSLSender() {
  1946. for {
  1947. // Await a signal that there are SLOKs to send
  1948. // TODO: use reflect.SelectCase, and optionally await timer here?
  1949. select {
  1950. case <-sshClient.signalIssueSLOKs:
  1951. case <-sshClient.runCtx.Done():
  1952. return
  1953. }
  1954. retryDelay := SSH_SEND_OSL_INITIAL_RETRY_DELAY
  1955. for {
  1956. err := sshClient.sendOSLRequest()
  1957. if err == nil {
  1958. break
  1959. }
  1960. if !isExpectedTunnelIOError(err) {
  1961. log.WithTraceFields(LogFields{"error": err}).Warning("sendOSLRequest failed")
  1962. }
  1963. // If the request failed, retry after a delay (with exponential backoff)
  1964. // or when signaled that there are additional SLOKs to send
  1965. retryTimer := time.NewTimer(retryDelay)
  1966. select {
  1967. case <-retryTimer.C:
  1968. case <-sshClient.signalIssueSLOKs:
  1969. case <-sshClient.runCtx.Done():
  1970. retryTimer.Stop()
  1971. return
  1972. }
  1973. retryTimer.Stop()
  1974. retryDelay *= SSH_SEND_OSL_RETRY_FACTOR
  1975. }
  1976. }
  1977. }
  1978. // sendOSLRequest will invoke osl.GetSeedPayload to issue SLOKs and
  1979. // generate a payload, and send an OSL request to the client when
  1980. // there are new SLOKs in the payload.
  1981. func (sshClient *sshClient) sendOSLRequest() error {
  1982. seedPayload := sshClient.getOSLSeedPayload()
  1983. // Don't send when no SLOKs. This will happen when signalIssueSLOKs
  1984. // is received but no new SLOKs are issued.
  1985. if len(seedPayload.SLOKs) == 0 {
  1986. return nil
  1987. }
  1988. oslRequest := protocol.OSLRequest{
  1989. SeedPayload: seedPayload,
  1990. }
  1991. requestPayload, err := json.Marshal(oslRequest)
  1992. if err != nil {
  1993. return errors.Trace(err)
  1994. }
  1995. ok, _, err := sshClient.sshConn.SendRequest(
  1996. protocol.PSIPHON_API_OSL_REQUEST_NAME,
  1997. true,
  1998. requestPayload)
  1999. if err != nil {
  2000. return errors.Trace(err)
  2001. }
  2002. if !ok {
  2003. return errors.TraceNew("client rejected request")
  2004. }
  2005. sshClient.clearOSLSeedPayload()
  2006. return nil
  2007. }
  2008. // runAlertSender dequeues and sends alert requests to the client. As these
  2009. // alerts are informational, there is no retry logic and no SSH client
  2010. // acknowledgement (wantReply) is requested. This worker scheme allows
  2011. // nonconcurrent components including udpgw and packet tunnel to enqueue
  2012. // alerts without blocking their traffic processing.
  2013. func (sshClient *sshClient) runAlertSender() {
  2014. for {
  2015. select {
  2016. case <-sshClient.runCtx.Done():
  2017. return
  2018. case request := <-sshClient.sendAlertRequests:
  2019. payload, err := json.Marshal(request)
  2020. if err != nil {
  2021. log.WithTraceFields(LogFields{"error": err}).Warning("Marshal failed")
  2022. break
  2023. }
  2024. _, _, err = sshClient.sshConn.SendRequest(
  2025. protocol.PSIPHON_API_ALERT_REQUEST_NAME,
  2026. false,
  2027. payload)
  2028. if err != nil && !isExpectedTunnelIOError(err) {
  2029. log.WithTraceFields(LogFields{"error": err}).Warning("SendRequest failed")
  2030. break
  2031. }
  2032. sshClient.Lock()
  2033. sshClient.sentAlertRequests[request] = true
  2034. sshClient.Unlock()
  2035. }
  2036. }
  2037. }
  2038. // enqueueAlertRequest enqueues an alert request to be sent to the client.
  2039. // Only one request is sent per tunnel per protocol.AlertRequest value;
  2040. // subsequent alerts with the same value are dropped. enqueueAlertRequest will
  2041. // not block until the queue exceeds ALERT_REQUEST_QUEUE_BUFFER_SIZE.
  2042. func (sshClient *sshClient) enqueueAlertRequest(request protocol.AlertRequest) {
  2043. sshClient.Lock()
  2044. if sshClient.sentAlertRequests[request] {
  2045. sshClient.Unlock()
  2046. return
  2047. }
  2048. sshClient.Unlock()
  2049. select {
  2050. case <-sshClient.runCtx.Done():
  2051. case sshClient.sendAlertRequests <- request:
  2052. }
  2053. }
  2054. func (sshClient *sshClient) enqueueDisallowedTrafficAlertRequest() {
  2055. sshClient.enqueueAlertRequest(protocol.AlertRequest{
  2056. Reason: protocol.PSIPHON_API_ALERT_DISALLOWED_TRAFFIC,
  2057. })
  2058. }
  2059. func (sshClient *sshClient) enqueueUnsafeTrafficAlertRequest(tags []BlocklistTag) {
  2060. for _, tag := range tags {
  2061. sshClient.enqueueAlertRequest(protocol.AlertRequest{
  2062. Reason: protocol.PSIPHON_API_ALERT_UNSAFE_TRAFFIC,
  2063. Subject: tag.Subject,
  2064. })
  2065. }
  2066. }
  2067. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, logMessage string) {
  2068. // We always return the reject reason "Prohibited":
  2069. // - Traffic rules and connection limits may prohibit the connection.
  2070. // - External firewall rules may prohibit the connection, and this is not currently
  2071. // distinguishable from other failure modes.
  2072. // - We limit the failure information revealed to the client.
  2073. reason := ssh.Prohibited
  2074. // Note: Debug level, as logMessage may contain user traffic destination address information
  2075. log.WithTraceFields(
  2076. LogFields{
  2077. "channelType": newChannel.ChannelType(),
  2078. "logMessage": logMessage,
  2079. "rejectReason": reason.String(),
  2080. }).Debug("reject new channel")
  2081. // Note: logMessage is internal, for logging only; just the reject reason is sent to the client.
  2082. newChannel.Reject(reason, reason.String())
  2083. }
  2084. // setHandshakeState records that a client has completed a handshake API request.
  2085. // Some parameters from the handshake request may be used in future traffic rule
  2086. // selection. Port forwards are disallowed until a handshake is complete. The
  2087. // handshake parameters are included in the session summary log recorded in
  2088. // sshClient.stop().
  2089. func (sshClient *sshClient) setHandshakeState(
  2090. state handshakeState,
  2091. authorizations []string) (*handshakeStateInfo, error) {
  2092. sshClient.Lock()
  2093. completed := sshClient.handshakeState.completed
  2094. if !completed {
  2095. sshClient.handshakeState = state
  2096. }
  2097. sshClient.Unlock()
  2098. // Client must only perform one handshake
  2099. if completed {
  2100. return nil, errors.TraceNew("handshake already completed")
  2101. }
  2102. // Verify the authorizations submitted by the client. Verified, active
  2103. // (non-expired) access types will be available for traffic rules
  2104. // filtering.
  2105. //
  2106. // When an authorization is active but expires while the client is
  2107. // connected, the client is disconnected to ensure the access is reset.
  2108. // This is implemented by setting a timer to perform the disconnect at the
  2109. // expiry time of the soonest expiring authorization.
  2110. //
  2111. // sshServer.authorizationSessionIDs tracks the unique mapping of active
  2112. // authorization IDs to client session IDs and is used to detect and
  2113. // prevent multiple malicious clients from reusing a single authorization
  2114. // (within the scope of this server).
  2115. // authorizationIDs and authorizedAccessTypes are returned to the client
  2116. // and logged, respectively; initialize to empty lists so the
  2117. // protocol/logs don't need to handle 'null' values.
  2118. authorizationIDs := make([]string, 0)
  2119. authorizedAccessTypes := make([]string, 0)
  2120. var stopTime time.Time
  2121. for i, authorization := range authorizations {
  2122. // This sanity check mitigates malicious clients causing excess CPU use.
  2123. if i >= MAX_AUTHORIZATIONS {
  2124. log.WithTrace().Warning("too many authorizations")
  2125. break
  2126. }
  2127. verifiedAuthorization, err := accesscontrol.VerifyAuthorization(
  2128. &sshClient.sshServer.support.Config.AccessControlVerificationKeyRing,
  2129. authorization)
  2130. if err != nil {
  2131. log.WithTraceFields(
  2132. LogFields{"error": err}).Warning("verify authorization failed")
  2133. continue
  2134. }
  2135. authorizationID := base64.StdEncoding.EncodeToString(verifiedAuthorization.ID)
  2136. if common.Contains(authorizedAccessTypes, verifiedAuthorization.AccessType) {
  2137. log.WithTraceFields(
  2138. LogFields{"accessType": verifiedAuthorization.AccessType}).Warning("duplicate authorization access type")
  2139. continue
  2140. }
  2141. authorizationIDs = append(authorizationIDs, authorizationID)
  2142. authorizedAccessTypes = append(authorizedAccessTypes, verifiedAuthorization.AccessType)
  2143. if stopTime.IsZero() || stopTime.After(verifiedAuthorization.Expires) {
  2144. stopTime = verifiedAuthorization.Expires
  2145. }
  2146. }
  2147. // Associate all verified authorizationIDs with this client's session ID.
  2148. // Handle cases where previous associations exist:
  2149. //
  2150. // - Multiple malicious clients reusing a single authorization. In this
  2151. // case, authorizations are revoked from the previous client.
  2152. //
  2153. // - The client reconnected with a new session ID due to user toggling.
  2154. // This case is expected due to server affinity. This cannot be
  2155. // distinguished from the previous case and the same action is taken;
  2156. // this will have no impact on a legitimate client as the previous
  2157. // session is dangling.
  2158. //
  2159. // - The client automatically reconnected with the same session ID. This
  2160. // case is not expected as sshServer.registerEstablishedClient
  2161. // synchronously calls sshClient.releaseAuthorizations; as a safe guard,
  2162. // this case is distinguished and no revocation action is taken.
  2163. sshClient.sshServer.authorizationSessionIDsMutex.Lock()
  2164. for _, authorizationID := range authorizationIDs {
  2165. sessionID, ok := sshClient.sshServer.authorizationSessionIDs[authorizationID]
  2166. if ok && sessionID != sshClient.sessionID {
  2167. logFields := LogFields{
  2168. "event_name": "irregular_tunnel",
  2169. "tunnel_error": "duplicate active authorization",
  2170. "duplicate_authorization_id": authorizationID,
  2171. }
  2172. sshClient.geoIPData.SetLogFields(logFields)
  2173. duplicateGeoIPData := sshClient.sshServer.support.GeoIPService.GetSessionCache(sessionID)
  2174. if duplicateGeoIPData != sshClient.geoIPData {
  2175. duplicateGeoIPData.SetLogFieldsWithPrefix("duplicate_authentication_", logFields)
  2176. }
  2177. log.LogRawFieldsWithTimestamp(logFields)
  2178. // Invoke asynchronously to avoid deadlocks.
  2179. // TODO: invoke only once for each distinct sessionID?
  2180. go sshClient.sshServer.revokeClientAuthorizations(sessionID)
  2181. }
  2182. sshClient.sshServer.authorizationSessionIDs[authorizationID] = sshClient.sessionID
  2183. }
  2184. sshClient.sshServer.authorizationSessionIDsMutex.Unlock()
  2185. if len(authorizationIDs) > 0 {
  2186. sshClient.Lock()
  2187. // Make the authorizedAccessTypes available for traffic rules filtering.
  2188. sshClient.handshakeState.authorizedAccessTypes = authorizedAccessTypes
  2189. // On exit, sshClient.runTunnel will call releaseAuthorizations, which
  2190. // will release the authorization IDs so the client can reconnect and
  2191. // present the same authorizations again. sshClient.runTunnel will
  2192. // also cancel the stopTimer in case it has not yet fired.
  2193. // Note: termination of the stopTimer goroutine is not synchronized.
  2194. sshClient.releaseAuthorizations = func() {
  2195. sshClient.sshServer.authorizationSessionIDsMutex.Lock()
  2196. for _, authorizationID := range authorizationIDs {
  2197. sessionID, ok := sshClient.sshServer.authorizationSessionIDs[authorizationID]
  2198. if ok && sessionID == sshClient.sessionID {
  2199. delete(sshClient.sshServer.authorizationSessionIDs, authorizationID)
  2200. }
  2201. }
  2202. sshClient.sshServer.authorizationSessionIDsMutex.Unlock()
  2203. }
  2204. sshClient.stopTimer = time.AfterFunc(
  2205. time.Until(stopTime),
  2206. func() {
  2207. sshClient.stop()
  2208. })
  2209. sshClient.Unlock()
  2210. }
  2211. upstreamBytesPerSecond, downstreamBytesPerSecond := sshClient.setTrafficRules()
  2212. sshClient.setOSLConfig()
  2213. return &handshakeStateInfo{
  2214. activeAuthorizationIDs: authorizationIDs,
  2215. authorizedAccessTypes: authorizedAccessTypes,
  2216. upstreamBytesPerSecond: upstreamBytesPerSecond,
  2217. downstreamBytesPerSecond: downstreamBytesPerSecond,
  2218. }, nil
  2219. }
  2220. // getHandshaked returns whether the client has completed a handshake API
  2221. // request and whether the traffic rules that were selected after the
  2222. // handshake immediately exhaust the client.
  2223. //
  2224. // When the client is immediately exhausted it will be closed; but this
  2225. // takes effect asynchronously. The "exhausted" return value is used to
  2226. // prevent API requests by clients that will close.
  2227. func (sshClient *sshClient) getHandshaked() (bool, bool) {
  2228. sshClient.Lock()
  2229. defer sshClient.Unlock()
  2230. completed := sshClient.handshakeState.completed
  2231. exhausted := false
  2232. // Notes:
  2233. // - "Immediately exhausted" is when CloseAfterExhausted is set and
  2234. // either ReadUnthrottledBytes or WriteUnthrottledBytes starts from
  2235. // 0, so no bytes would be read or written. This check does not
  2236. // examine whether 0 bytes _remain_ in the ThrottledConn.
  2237. // - This check is made against the current traffic rules, which
  2238. // could have changed in a hot reload since the handshake.
  2239. if completed &&
  2240. *sshClient.trafficRules.RateLimits.CloseAfterExhausted &&
  2241. (*sshClient.trafficRules.RateLimits.ReadUnthrottledBytes == 0 ||
  2242. *sshClient.trafficRules.RateLimits.WriteUnthrottledBytes == 0) {
  2243. exhausted = true
  2244. }
  2245. return completed, exhausted
  2246. }
  2247. func (sshClient *sshClient) updateAPIParameters(
  2248. apiParams common.APIParameters) {
  2249. sshClient.Lock()
  2250. defer sshClient.Unlock()
  2251. // Only update after handshake has initialized API params.
  2252. if !sshClient.handshakeState.completed {
  2253. return
  2254. }
  2255. for name, value := range apiParams {
  2256. sshClient.handshakeState.apiParams[name] = value
  2257. }
  2258. }
  2259. func (sshClient *sshClient) expectDomainBytes() bool {
  2260. sshClient.Lock()
  2261. defer sshClient.Unlock()
  2262. return sshClient.handshakeState.expectDomainBytes
  2263. }
  2264. // setTrafficRules resets the client's traffic rules based on the latest server config
  2265. // and client properties. As sshClient.trafficRules may be reset by a concurrent
  2266. // goroutine, trafficRules must only be accessed within the sshClient mutex.
  2267. func (sshClient *sshClient) setTrafficRules() (int64, int64) {
  2268. sshClient.Lock()
  2269. defer sshClient.Unlock()
  2270. isFirstTunnelInSession := sshClient.isFirstTunnelInSession &&
  2271. sshClient.handshakeState.establishedTunnelsCount == 0
  2272. sshClient.trafficRules = sshClient.sshServer.support.TrafficRulesSet.GetTrafficRules(
  2273. isFirstTunnelInSession,
  2274. sshClient.tunnelProtocol,
  2275. sshClient.geoIPData,
  2276. sshClient.handshakeState)
  2277. if sshClient.throttledConn != nil {
  2278. // Any existing throttling state is reset.
  2279. sshClient.throttledConn.SetLimits(
  2280. sshClient.trafficRules.RateLimits.CommonRateLimits())
  2281. }
  2282. return *sshClient.trafficRules.RateLimits.ReadBytesPerSecond,
  2283. *sshClient.trafficRules.RateLimits.WriteBytesPerSecond
  2284. }
  2285. // setOSLConfig resets the client's OSL seed state based on the latest OSL config
  2286. // As sshClient.oslClientSeedState may be reset by a concurrent goroutine,
  2287. // oslClientSeedState must only be accessed within the sshClient mutex.
  2288. func (sshClient *sshClient) setOSLConfig() {
  2289. sshClient.Lock()
  2290. defer sshClient.Unlock()
  2291. propagationChannelID, err := getStringRequestParam(
  2292. sshClient.handshakeState.apiParams, "propagation_channel_id")
  2293. if err != nil {
  2294. // This should not fail as long as client has sent valid handshake
  2295. return
  2296. }
  2297. // Use a cached seed state if one is found for the client's
  2298. // session ID. This enables resuming progress made in a previous
  2299. // tunnel.
  2300. // Note: go-cache is already concurency safe; the additional mutex
  2301. // is necessary to guarantee that Get/Delete is atomic; although in
  2302. // practice no two concurrent clients should ever supply the same
  2303. // session ID.
  2304. sshClient.sshServer.oslSessionCacheMutex.Lock()
  2305. oslClientSeedState, found := sshClient.sshServer.oslSessionCache.Get(sshClient.sessionID)
  2306. if found {
  2307. sshClient.sshServer.oslSessionCache.Delete(sshClient.sessionID)
  2308. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  2309. sshClient.oslClientSeedState = oslClientSeedState.(*osl.ClientSeedState)
  2310. sshClient.oslClientSeedState.Resume(sshClient.signalIssueSLOKs)
  2311. return
  2312. }
  2313. sshClient.sshServer.oslSessionCacheMutex.Unlock()
  2314. // Two limitations when setOSLConfig() is invoked due to an
  2315. // OSL config hot reload:
  2316. //
  2317. // 1. any partial progress towards SLOKs is lost.
  2318. //
  2319. // 2. all existing osl.ClientSeedPortForwards for existing
  2320. // port forwards will not send progress to the new client
  2321. // seed state.
  2322. sshClient.oslClientSeedState = sshClient.sshServer.support.OSLConfig.NewClientSeedState(
  2323. sshClient.geoIPData.Country,
  2324. propagationChannelID,
  2325. sshClient.signalIssueSLOKs)
  2326. }
  2327. // newClientSeedPortForward will return nil when no seeding is
  2328. // associated with the specified ipAddress.
  2329. func (sshClient *sshClient) newClientSeedPortForward(ipAddress net.IP) *osl.ClientSeedPortForward {
  2330. sshClient.Lock()
  2331. defer sshClient.Unlock()
  2332. // Will not be initialized before handshake.
  2333. if sshClient.oslClientSeedState == nil {
  2334. return nil
  2335. }
  2336. return sshClient.oslClientSeedState.NewClientSeedPortForward(ipAddress)
  2337. }
  2338. // getOSLSeedPayload returns a payload containing all seeded SLOKs for
  2339. // this client's session.
  2340. func (sshClient *sshClient) getOSLSeedPayload() *osl.SeedPayload {
  2341. sshClient.Lock()
  2342. defer sshClient.Unlock()
  2343. // Will not be initialized before handshake.
  2344. if sshClient.oslClientSeedState == nil {
  2345. return &osl.SeedPayload{SLOKs: make([]*osl.SLOK, 0)}
  2346. }
  2347. return sshClient.oslClientSeedState.GetSeedPayload()
  2348. }
  2349. func (sshClient *sshClient) clearOSLSeedPayload() {
  2350. sshClient.Lock()
  2351. defer sshClient.Unlock()
  2352. sshClient.oslClientSeedState.ClearSeedPayload()
  2353. }
  2354. func (sshClient *sshClient) rateLimits() common.RateLimits {
  2355. sshClient.Lock()
  2356. defer sshClient.Unlock()
  2357. return sshClient.trafficRules.RateLimits.CommonRateLimits()
  2358. }
  2359. func (sshClient *sshClient) idleTCPPortForwardTimeout() time.Duration {
  2360. sshClient.Lock()
  2361. defer sshClient.Unlock()
  2362. return time.Duration(*sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds) * time.Millisecond
  2363. }
  2364. func (sshClient *sshClient) idleUDPPortForwardTimeout() time.Duration {
  2365. sshClient.Lock()
  2366. defer sshClient.Unlock()
  2367. return time.Duration(*sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds) * time.Millisecond
  2368. }
  2369. func (sshClient *sshClient) setTCPPortForwardDialingAvailableSignal(signal context.CancelFunc) {
  2370. sshClient.Lock()
  2371. defer sshClient.Unlock()
  2372. sshClient.tcpPortForwardDialingAvailableSignal = signal
  2373. }
  2374. const (
  2375. portForwardTypeTCP = iota
  2376. portForwardTypeUDP
  2377. )
  2378. func (sshClient *sshClient) isPortForwardPermitted(
  2379. portForwardType int,
  2380. remoteIP net.IP,
  2381. port int) bool {
  2382. // Disallow connection to loopback. This is a failsafe. The server
  2383. // should be run on a host with correctly configured firewall rules.
  2384. if remoteIP.IsLoopback() {
  2385. return false
  2386. }
  2387. // Blocklist check.
  2388. //
  2389. // Limitation: isPortForwardPermitted is not called in transparent DNS
  2390. // forwarding cases. As the destination IP address is rewritten in these
  2391. // cases, a blocklist entry won't be dialed in any case. However, no logs
  2392. // will be recorded.
  2393. tags := sshClient.sshServer.support.Blocklist.LookupIP(remoteIP)
  2394. if len(tags) > 0 {
  2395. sshClient.logBlocklistHits(remoteIP, "", tags)
  2396. if sshClient.sshServer.support.Config.BlocklistActive {
  2397. // Actively alert and block
  2398. sshClient.enqueueUnsafeTrafficAlertRequest(tags)
  2399. return false
  2400. }
  2401. }
  2402. // Don't lock before calling logBlocklistHits.
  2403. // Unlock before calling enqueueDisallowedTrafficAlertRequest/log.
  2404. sshClient.Lock()
  2405. allowed := true
  2406. // Client must complete handshake before port forwards are permitted.
  2407. if !sshClient.handshakeState.completed {
  2408. allowed = false
  2409. }
  2410. if allowed {
  2411. // Traffic rules checks.
  2412. switch portForwardType {
  2413. case portForwardTypeTCP:
  2414. if !sshClient.trafficRules.AllowTCPPort(remoteIP, port) {
  2415. allowed = false
  2416. }
  2417. case portForwardTypeUDP:
  2418. if !sshClient.trafficRules.AllowUDPPort(remoteIP, port) {
  2419. allowed = false
  2420. }
  2421. }
  2422. }
  2423. sshClient.Unlock()
  2424. if allowed {
  2425. return true
  2426. }
  2427. switch portForwardType {
  2428. case portForwardTypeTCP:
  2429. sshClient.updateQualityMetricsWithTCPRejectedDisallowed()
  2430. case portForwardTypeUDP:
  2431. sshClient.updateQualityMetricsWithUDPRejectedDisallowed()
  2432. }
  2433. sshClient.enqueueDisallowedTrafficAlertRequest()
  2434. log.WithTraceFields(
  2435. LogFields{
  2436. "type": portForwardType,
  2437. "port": port,
  2438. }).Debug("port forward denied by traffic rules")
  2439. return false
  2440. }
  2441. func (sshClient *sshClient) isTCPDialingPortForwardLimitExceeded() bool {
  2442. sshClient.Lock()
  2443. defer sshClient.Unlock()
  2444. state := &sshClient.tcpTrafficState
  2445. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  2446. if max > 0 && state.concurrentDialingPortForwardCount >= int64(max) {
  2447. return true
  2448. }
  2449. return false
  2450. }
  2451. func (sshClient *sshClient) getTCPPortForwardQueueSize() int {
  2452. sshClient.Lock()
  2453. defer sshClient.Unlock()
  2454. return *sshClient.trafficRules.MaxTCPPortForwardCount +
  2455. *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  2456. }
  2457. func (sshClient *sshClient) getDialTCPPortForwardTimeoutMilliseconds() int {
  2458. sshClient.Lock()
  2459. defer sshClient.Unlock()
  2460. return *sshClient.trafficRules.DialTCPPortForwardTimeoutMilliseconds
  2461. }
  2462. func (sshClient *sshClient) dialingTCPPortForward() {
  2463. sshClient.Lock()
  2464. defer sshClient.Unlock()
  2465. state := &sshClient.tcpTrafficState
  2466. state.concurrentDialingPortForwardCount += 1
  2467. if state.concurrentDialingPortForwardCount > state.peakConcurrentDialingPortForwardCount {
  2468. state.peakConcurrentDialingPortForwardCount = state.concurrentDialingPortForwardCount
  2469. }
  2470. }
  2471. func (sshClient *sshClient) abortedTCPPortForward() {
  2472. sshClient.Lock()
  2473. defer sshClient.Unlock()
  2474. sshClient.tcpTrafficState.concurrentDialingPortForwardCount -= 1
  2475. }
  2476. func (sshClient *sshClient) allocatePortForward(portForwardType int) bool {
  2477. sshClient.Lock()
  2478. defer sshClient.Unlock()
  2479. // Check if at port forward limit. The subsequent counter
  2480. // changes must be atomic with the limit check to ensure
  2481. // the counter never exceeds the limit in the case of
  2482. // concurrent allocations.
  2483. var max int
  2484. var state *trafficState
  2485. if portForwardType == portForwardTypeTCP {
  2486. max = *sshClient.trafficRules.MaxTCPPortForwardCount
  2487. state = &sshClient.tcpTrafficState
  2488. } else {
  2489. max = *sshClient.trafficRules.MaxUDPPortForwardCount
  2490. state = &sshClient.udpTrafficState
  2491. }
  2492. if max > 0 && state.concurrentPortForwardCount >= int64(max) {
  2493. return false
  2494. }
  2495. // Update port forward counters.
  2496. if portForwardType == portForwardTypeTCP {
  2497. // Assumes TCP port forwards called dialingTCPPortForward
  2498. state.concurrentDialingPortForwardCount -= 1
  2499. if sshClient.tcpPortForwardDialingAvailableSignal != nil {
  2500. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  2501. if max <= 0 || state.concurrentDialingPortForwardCount < int64(max) {
  2502. sshClient.tcpPortForwardDialingAvailableSignal()
  2503. }
  2504. }
  2505. }
  2506. state.concurrentPortForwardCount += 1
  2507. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  2508. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  2509. }
  2510. state.totalPortForwardCount += 1
  2511. return true
  2512. }
  2513. // establishedPortForward increments the concurrent port
  2514. // forward counter. closedPortForward decrements it, so it
  2515. // must always be called for each establishedPortForward
  2516. // call.
  2517. //
  2518. // When at the limit of established port forwards, the LRU
  2519. // existing port forward is closed to make way for the newly
  2520. // established one. There can be a minor delay as, in addition
  2521. // to calling Close() on the port forward net.Conn,
  2522. // establishedPortForward waits for the LRU's closedPortForward()
  2523. // call which will decrement the concurrent counter. This
  2524. // ensures all resources associated with the LRU (socket,
  2525. // goroutine) are released or will very soon be released before
  2526. // proceeding.
  2527. func (sshClient *sshClient) establishedPortForward(
  2528. portForwardType int, portForwardLRU *common.LRUConns) {
  2529. // Do not lock sshClient here.
  2530. var state *trafficState
  2531. if portForwardType == portForwardTypeTCP {
  2532. state = &sshClient.tcpTrafficState
  2533. } else {
  2534. state = &sshClient.udpTrafficState
  2535. }
  2536. // When the maximum number of port forwards is already
  2537. // established, close the LRU. CloseOldest will call
  2538. // Close on the port forward net.Conn. Both TCP and
  2539. // UDP port forwards have handler goroutines that may
  2540. // be blocked calling Read on the net.Conn. Close will
  2541. // eventually interrupt the Read and cause the handlers
  2542. // to exit, but not immediately. So the following logic
  2543. // waits for a LRU handler to be interrupted and signal
  2544. // availability.
  2545. //
  2546. // Notes:
  2547. //
  2548. // - the port forward limit can change via a traffic
  2549. // rules hot reload; the condition variable handles
  2550. // this case whereas a channel-based semaphore would
  2551. // not.
  2552. //
  2553. // - if a number of goroutines exceeding the total limit
  2554. // arrive here all concurrently, some CloseOldest() calls
  2555. // will have no effect as there can be less existing port
  2556. // forwards than new ones. In this case, the new port
  2557. // forward will be delayed. This is highly unlikely in
  2558. // practise since UDP calls to establishedPortForward are
  2559. // serialized and TCP calls are limited by the dial
  2560. // queue/count.
  2561. if !sshClient.allocatePortForward(portForwardType) {
  2562. portForwardLRU.CloseOldest()
  2563. log.WithTrace().Debug("closed LRU port forward")
  2564. state.availablePortForwardCond.L.Lock()
  2565. for !sshClient.allocatePortForward(portForwardType) {
  2566. state.availablePortForwardCond.Wait()
  2567. }
  2568. state.availablePortForwardCond.L.Unlock()
  2569. }
  2570. }
  2571. func (sshClient *sshClient) closedPortForward(
  2572. portForwardType int, bytesUp, bytesDown int64) {
  2573. sshClient.Lock()
  2574. var state *trafficState
  2575. if portForwardType == portForwardTypeTCP {
  2576. state = &sshClient.tcpTrafficState
  2577. } else {
  2578. state = &sshClient.udpTrafficState
  2579. }
  2580. state.concurrentPortForwardCount -= 1
  2581. state.bytesUp += bytesUp
  2582. state.bytesDown += bytesDown
  2583. sshClient.Unlock()
  2584. // Signal any goroutine waiting in establishedPortForward
  2585. // that an established port forward slot is available.
  2586. state.availablePortForwardCond.Signal()
  2587. }
  2588. func (sshClient *sshClient) updateQualityMetricsWithDialResult(
  2589. tcpPortForwardDialSuccess bool, dialDuration time.Duration, IP net.IP) {
  2590. sshClient.Lock()
  2591. defer sshClient.Unlock()
  2592. if tcpPortForwardDialSuccess {
  2593. sshClient.qualityMetrics.TCPPortForwardDialedCount += 1
  2594. sshClient.qualityMetrics.TCPPortForwardDialedDuration += dialDuration
  2595. if IP.To4() != nil {
  2596. sshClient.qualityMetrics.TCPIPv4PortForwardDialedCount += 1
  2597. sshClient.qualityMetrics.TCPIPv4PortForwardDialedDuration += dialDuration
  2598. } else if IP != nil {
  2599. sshClient.qualityMetrics.TCPIPv6PortForwardDialedCount += 1
  2600. sshClient.qualityMetrics.TCPIPv6PortForwardDialedDuration += dialDuration
  2601. }
  2602. } else {
  2603. sshClient.qualityMetrics.TCPPortForwardFailedCount += 1
  2604. sshClient.qualityMetrics.TCPPortForwardFailedDuration += dialDuration
  2605. if IP.To4() != nil {
  2606. sshClient.qualityMetrics.TCPIPv4PortForwardFailedCount += 1
  2607. sshClient.qualityMetrics.TCPIPv4PortForwardFailedDuration += dialDuration
  2608. } else if IP != nil {
  2609. sshClient.qualityMetrics.TCPIPv6PortForwardFailedCount += 1
  2610. sshClient.qualityMetrics.TCPIPv6PortForwardFailedDuration += dialDuration
  2611. }
  2612. }
  2613. }
  2614. func (sshClient *sshClient) updateQualityMetricsWithRejectedDialingLimit() {
  2615. sshClient.Lock()
  2616. defer sshClient.Unlock()
  2617. sshClient.qualityMetrics.TCPPortForwardRejectedDialingLimitCount += 1
  2618. }
  2619. func (sshClient *sshClient) updateQualityMetricsWithTCPRejectedDisallowed() {
  2620. sshClient.Lock()
  2621. defer sshClient.Unlock()
  2622. sshClient.qualityMetrics.TCPPortForwardRejectedDisallowedCount += 1
  2623. }
  2624. func (sshClient *sshClient) updateQualityMetricsWithUDPRejectedDisallowed() {
  2625. sshClient.Lock()
  2626. defer sshClient.Unlock()
  2627. sshClient.qualityMetrics.UDPPortForwardRejectedDisallowedCount += 1
  2628. }
  2629. func (sshClient *sshClient) handleTCPChannel(
  2630. remainingDialTimeout time.Duration,
  2631. hostToConnect string,
  2632. portToConnect int,
  2633. newChannel ssh.NewChannel) {
  2634. // Assumptions:
  2635. // - sshClient.dialingTCPPortForward() has been called
  2636. // - remainingDialTimeout > 0
  2637. established := false
  2638. defer func() {
  2639. if !established {
  2640. sshClient.abortedTCPPortForward()
  2641. }
  2642. }()
  2643. // Transparently redirect web API request connections.
  2644. isWebServerPortForward := false
  2645. config := sshClient.sshServer.support.Config
  2646. if config.WebServerPortForwardAddress != "" {
  2647. destination := net.JoinHostPort(hostToConnect, strconv.Itoa(portToConnect))
  2648. if destination == config.WebServerPortForwardAddress {
  2649. isWebServerPortForward = true
  2650. if config.WebServerPortForwardRedirectAddress != "" {
  2651. // Note: redirect format is validated when config is loaded
  2652. host, portStr, _ := net.SplitHostPort(config.WebServerPortForwardRedirectAddress)
  2653. port, _ := strconv.Atoi(portStr)
  2654. hostToConnect = host
  2655. portToConnect = port
  2656. }
  2657. }
  2658. }
  2659. // Validate the domain name and check the domain blocklist before dialing.
  2660. //
  2661. // The IP blocklist is checked in isPortForwardPermitted, which also provides
  2662. // IP blocklist checking for the packet tunnel code path. When hostToConnect
  2663. // is an IP address, the following hostname resolution step effectively
  2664. // performs no actions and next immediate step is the isPortForwardPermitted
  2665. // check.
  2666. //
  2667. // Limitation: at this time, only clients that send domains in hostToConnect
  2668. // are subject to domain blocklist checks. Both the udpgw and packet tunnel
  2669. // modes perform tunneled DNS and send only IPs in hostToConnect.
  2670. if !isWebServerPortForward &&
  2671. net.ParseIP(hostToConnect) == nil {
  2672. // We're not doing comprehensive validation, to avoid overhead per port
  2673. // forward. This is a simple sanity check to ensure we don't process
  2674. // blantantly invalid input.
  2675. //
  2676. // TODO: validate with dns.IsDomainName?
  2677. if len(hostToConnect) > 255 {
  2678. // Note: not recording a port forward failure in this case
  2679. sshClient.rejectNewChannel(newChannel, "invalid domain name")
  2680. return
  2681. }
  2682. tags := sshClient.sshServer.support.Blocklist.LookupDomain(hostToConnect)
  2683. if len(tags) > 0 {
  2684. sshClient.logBlocklistHits(nil, hostToConnect, tags)
  2685. if sshClient.sshServer.support.Config.BlocklistActive {
  2686. // Actively alert and block
  2687. // Note: not recording a port forward failure in this case
  2688. sshClient.enqueueUnsafeTrafficAlertRequest(tags)
  2689. sshClient.rejectNewChannel(newChannel, "port forward not permitted")
  2690. return
  2691. }
  2692. }
  2693. }
  2694. // Dial the remote address.
  2695. //
  2696. // Hostname resolution is performed explicitly, as a separate step, as the
  2697. // target IP address is used for traffic rules (AllowSubnets), OSL seed
  2698. // progress, and IP address blocklists.
  2699. //
  2700. // Contexts are used for cancellation (via sshClient.runCtx, which is
  2701. // cancelled when the client is stopping) and timeouts.
  2702. dialStartTime := time.Now()
  2703. log.WithTraceFields(LogFields{"hostToConnect": hostToConnect}).Debug("resolving")
  2704. ctx, cancelCtx := context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  2705. IPs, err := (&net.Resolver{}).LookupIPAddr(ctx, hostToConnect)
  2706. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  2707. // IPv4 is preferred in case the host has limited IPv6 routing. IPv6 is
  2708. // selected and attempted only when there's no IPv4 option.
  2709. // TODO: shuffle list to try other IPs?
  2710. var IP net.IP
  2711. for _, ip := range IPs {
  2712. if ip.IP.To4() != nil {
  2713. IP = ip.IP
  2714. break
  2715. }
  2716. }
  2717. if IP == nil && len(IPs) > 0 {
  2718. // If there are no IPv4 IPs, the first IP is IPv6.
  2719. IP = IPs[0].IP
  2720. }
  2721. if err == nil && IP == nil {
  2722. err = std_errors.New("no IP address")
  2723. }
  2724. resolveElapsedTime := time.Since(dialStartTime)
  2725. if err != nil {
  2726. // Record a port forward failure
  2727. sshClient.updateQualityMetricsWithDialResult(false, resolveElapsedTime, IP)
  2728. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("LookupIP failed: %s", err))
  2729. return
  2730. }
  2731. remainingDialTimeout -= resolveElapsedTime
  2732. if remainingDialTimeout <= 0 {
  2733. sshClient.rejectNewChannel(newChannel, "TCP port forward timed out resolving")
  2734. return
  2735. }
  2736. // Enforce traffic rules, using the resolved IP address.
  2737. if !isWebServerPortForward &&
  2738. !sshClient.isPortForwardPermitted(
  2739. portForwardTypeTCP,
  2740. IP,
  2741. portToConnect) {
  2742. // Note: not recording a port forward failure in this case
  2743. sshClient.rejectNewChannel(newChannel, "port forward not permitted")
  2744. return
  2745. }
  2746. // TCP dial.
  2747. remoteAddr := net.JoinHostPort(IP.String(), strconv.Itoa(portToConnect))
  2748. log.WithTraceFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  2749. ctx, cancelCtx = context.WithTimeout(sshClient.runCtx, remainingDialTimeout)
  2750. fwdConn, err := (&net.Dialer{}).DialContext(ctx, "tcp", remoteAddr)
  2751. cancelCtx() // "must be called or the new context will remain live until its parent context is cancelled"
  2752. // Record port forward success or failure
  2753. sshClient.updateQualityMetricsWithDialResult(err == nil, time.Since(dialStartTime), IP)
  2754. if err != nil {
  2755. // Monitor for low resource error conditions
  2756. sshClient.sshServer.monitorPortForwardDialError(err)
  2757. sshClient.rejectNewChannel(newChannel, fmt.Sprintf("DialTimeout failed: %s", err))
  2758. return
  2759. }
  2760. // The upstream TCP port forward connection has been established. Schedule
  2761. // some cleanup and notify the SSH client that the channel is accepted.
  2762. defer fwdConn.Close()
  2763. fwdChannel, requests, err := newChannel.Accept()
  2764. if err != nil {
  2765. if !isExpectedTunnelIOError(err) {
  2766. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  2767. }
  2768. return
  2769. }
  2770. go ssh.DiscardRequests(requests)
  2771. defer fwdChannel.Close()
  2772. // Release the dialing slot and acquire an established slot.
  2773. //
  2774. // establishedPortForward increments the concurrent TCP port
  2775. // forward counter and closes the LRU existing TCP port forward
  2776. // when already at the limit.
  2777. //
  2778. // Known limitations:
  2779. //
  2780. // - Closed LRU TCP sockets will enter the TIME_WAIT state,
  2781. // continuing to consume some resources.
  2782. sshClient.establishedPortForward(portForwardTypeTCP, sshClient.tcpPortForwardLRU)
  2783. // "established = true" cancels the deferred abortedTCPPortForward()
  2784. established = true
  2785. // TODO: 64-bit alignment? https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  2786. var bytesUp, bytesDown int64
  2787. defer func() {
  2788. sshClient.closedPortForward(
  2789. portForwardTypeTCP, atomic.LoadInt64(&bytesUp), atomic.LoadInt64(&bytesDown))
  2790. }()
  2791. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  2792. defer lruEntry.Remove()
  2793. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  2794. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  2795. // forward if both reads and writes have been idle for the specified
  2796. // duration.
  2797. // Ensure nil interface if newClientSeedPortForward returns nil
  2798. var updater common.ActivityUpdater
  2799. seedUpdater := sshClient.newClientSeedPortForward(IP)
  2800. if seedUpdater != nil {
  2801. updater = seedUpdater
  2802. }
  2803. fwdConn, err = common.NewActivityMonitoredConn(
  2804. fwdConn,
  2805. sshClient.idleTCPPortForwardTimeout(),
  2806. true,
  2807. updater,
  2808. lruEntry)
  2809. if err != nil {
  2810. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  2811. return
  2812. }
  2813. // Relay channel to forwarded connection.
  2814. log.WithTraceFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  2815. // TODO: relay errors to fwdChannel.Stderr()?
  2816. relayWaitGroup := new(sync.WaitGroup)
  2817. relayWaitGroup.Add(1)
  2818. go func() {
  2819. defer relayWaitGroup.Done()
  2820. // io.Copy allocates a 32K temporary buffer, and each port forward relay
  2821. // uses two of these buffers; using common.CopyBuffer with a smaller buffer
  2822. // reduces the overall memory footprint.
  2823. bytes, err := common.CopyBuffer(
  2824. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  2825. atomic.AddInt64(&bytesDown, bytes)
  2826. if err != nil && err != io.EOF {
  2827. // Debug since errors such as "connection reset by peer" occur during normal operation
  2828. log.WithTraceFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  2829. }
  2830. // Interrupt upstream io.Copy when downstream is shutting down.
  2831. // TODO: this is done to quickly cleanup the port forward when
  2832. // fwdConn has a read timeout, but is it clean -- upstream may still
  2833. // be flowing?
  2834. fwdChannel.Close()
  2835. }()
  2836. bytes, err := common.CopyBuffer(
  2837. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  2838. atomic.AddInt64(&bytesUp, bytes)
  2839. if err != nil && err != io.EOF {
  2840. log.WithTraceFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  2841. }
  2842. // Shutdown special case: fwdChannel will be closed and return EOF when
  2843. // the SSH connection is closed, but we need to explicitly close fwdConn
  2844. // to interrupt the downstream io.Copy, which may be blocked on a
  2845. // fwdConn.Read().
  2846. fwdConn.Close()
  2847. relayWaitGroup.Wait()
  2848. log.WithTraceFields(
  2849. LogFields{
  2850. "remoteAddr": remoteAddr,
  2851. "bytesUp": atomic.LoadInt64(&bytesUp),
  2852. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  2853. }