tunnelServer.go 104 KB

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