tunnelServer.go 91 KB

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