tunnelServer.go 87 KB

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