tunnelServer.go 82 KB

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