tailssh.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux || (darwin && !ios) || freebsd || openbsd
  4. // Package tailssh is an SSH server integrated into Tailscale.
  5. package tailssh
  6. import (
  7. "bytes"
  8. "context"
  9. "crypto/rand"
  10. "encoding/base64"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "net/http"
  17. "net/http/httptrace"
  18. "net/netip"
  19. "net/url"
  20. "os"
  21. "os/exec"
  22. "path/filepath"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "syscall"
  29. "time"
  30. gossh "github.com/tailscale/golang-x-crypto/ssh"
  31. "tailscale.com/envknob"
  32. "tailscale.com/ipn/ipnlocal"
  33. "tailscale.com/logtail/backoff"
  34. "tailscale.com/net/tsaddr"
  35. "tailscale.com/net/tsdial"
  36. "tailscale.com/tailcfg"
  37. "tailscale.com/tempfork/gliderlabs/ssh"
  38. "tailscale.com/types/key"
  39. "tailscale.com/types/logger"
  40. "tailscale.com/types/netmap"
  41. "tailscale.com/util/clientmetric"
  42. "tailscale.com/util/httpm"
  43. "tailscale.com/util/mak"
  44. "tailscale.com/util/multierr"
  45. )
  46. var (
  47. sshVerboseLogging = envknob.RegisterBool("TS_DEBUG_SSH_VLOG")
  48. sshDisableSFTP = envknob.RegisterBool("TS_SSH_DISABLE_SFTP")
  49. sshDisableForwarding = envknob.RegisterBool("TS_SSH_DISABLE_FORWARDING")
  50. sshDisablePTY = envknob.RegisterBool("TS_SSH_DISABLE_PTY")
  51. )
  52. const (
  53. // forcePasswordSuffix is the suffix at the end of a username that forces
  54. // Tailscale SSH into password authentication mode to work around buggy SSH
  55. // clients that get confused by successful replies to auth type "none".
  56. forcePasswordSuffix = "+password"
  57. )
  58. // ipnLocalBackend is the subset of ipnlocal.LocalBackend that we use.
  59. // It is used for testing.
  60. type ipnLocalBackend interface {
  61. GetSSH_HostKeys() ([]gossh.Signer, error)
  62. ShouldRunSSH() bool
  63. NetMap() *netmap.NetworkMap
  64. WhoIs(ipp netip.AddrPort) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool)
  65. DoNoiseRequest(req *http.Request) (*http.Response, error)
  66. Dialer() *tsdial.Dialer
  67. TailscaleVarRoot() string
  68. NodeKey() key.NodePublic
  69. }
  70. type server struct {
  71. lb ipnLocalBackend
  72. logf logger.Logf
  73. tailscaledPath string
  74. pubKeyHTTPClient *http.Client // or nil for http.DefaultClient
  75. timeNow func() time.Time // or nil for time.Now
  76. sessionWaitGroup sync.WaitGroup
  77. // mu protects the following
  78. mu sync.Mutex
  79. activeConns map[*conn]bool // set; value is always true
  80. fetchPublicKeysCache map[string]pubKeyCacheEntry // by https URL
  81. shutdownCalled bool
  82. }
  83. func (srv *server) now() time.Time {
  84. if srv != nil && srv.timeNow != nil {
  85. return srv.timeNow()
  86. }
  87. return time.Now()
  88. }
  89. func init() {
  90. ipnlocal.RegisterNewSSHServer(func(logf logger.Logf, lb *ipnlocal.LocalBackend) (ipnlocal.SSHServer, error) {
  91. tsd, err := os.Executable()
  92. if err != nil {
  93. return nil, err
  94. }
  95. srv := &server{
  96. lb: lb,
  97. logf: logf,
  98. tailscaledPath: tsd,
  99. timeNow: func() time.Time {
  100. return lb.ControlNow(time.Now())
  101. },
  102. }
  103. return srv, nil
  104. })
  105. }
  106. // attachSessionToConnIfNotShutdown ensures that srv is not shutdown before
  107. // attaching the session to the conn. This ensures that once Shutdown is called,
  108. // new sessions are not allowed and existing ones are cleaned up.
  109. // It reports whether ss was attached to the conn.
  110. func (srv *server) attachSessionToConnIfNotShutdown(ss *sshSession) bool {
  111. srv.mu.Lock()
  112. defer srv.mu.Unlock()
  113. if srv.shutdownCalled {
  114. // Do not start any new sessions.
  115. return false
  116. }
  117. ss.conn.attachSession(ss)
  118. return true
  119. }
  120. func (srv *server) trackActiveConn(c *conn, add bool) {
  121. srv.mu.Lock()
  122. defer srv.mu.Unlock()
  123. if add {
  124. mak.Set(&srv.activeConns, c, true)
  125. return
  126. }
  127. delete(srv.activeConns, c)
  128. }
  129. // HandleSSHConn handles a Tailscale SSH connection from c.
  130. // This is the entry point for all SSH connections.
  131. // When this returns, the connection is closed.
  132. func (srv *server) HandleSSHConn(nc net.Conn) error {
  133. metricIncomingConnections.Add(1)
  134. c, err := srv.newConn()
  135. if err != nil {
  136. return err
  137. }
  138. srv.trackActiveConn(c, true) // add
  139. defer srv.trackActiveConn(c, false) // remove
  140. c.HandleConn(nc)
  141. // Return nil to signal to netstack's interception that it doesn't need to
  142. // log. If ss.HandleConn had problems, it can log itself (ideally on an
  143. // sshSession.logf).
  144. return nil
  145. }
  146. // Shutdown terminates all active sessions.
  147. func (srv *server) Shutdown() {
  148. srv.mu.Lock()
  149. srv.shutdownCalled = true
  150. for c := range srv.activeConns {
  151. c.Close()
  152. }
  153. srv.mu.Unlock()
  154. srv.sessionWaitGroup.Wait()
  155. }
  156. // OnPolicyChange terminates any active sessions that no longer match
  157. // the SSH access policy.
  158. func (srv *server) OnPolicyChange() {
  159. srv.mu.Lock()
  160. defer srv.mu.Unlock()
  161. for c := range srv.activeConns {
  162. if c.info == nil {
  163. // c.info is nil when the connection hasn't been authenticated yet.
  164. // In that case, the connection will be terminated when it is.
  165. continue
  166. }
  167. go c.checkStillValid()
  168. }
  169. }
  170. // conn represents a single SSH connection and its associated
  171. // ssh.Server.
  172. //
  173. // During the lifecycle of a connection, the following are called in order:
  174. // Setup and discover server info
  175. // - ServerConfigCallback
  176. //
  177. // Do the user auth
  178. // - NoClientAuthHandler
  179. // - PublicKeyHandler (only if NoClientAuthHandler returns errPubKeyRequired)
  180. //
  181. // Once auth is done, the conn can be multiplexed with multiple sessions and
  182. // channels concurrently. At which point any of the following can be called
  183. // in any order.
  184. // - c.handleSessionPostSSHAuth
  185. // - c.mayForwardLocalPortTo followed by ssh.DirectTCPIPHandler
  186. type conn struct {
  187. *ssh.Server
  188. srv *server
  189. insecureSkipTailscaleAuth bool // used by tests.
  190. // idH is the RFC4253 sec8 hash H. It is used to identify the connection,
  191. // and is shared among all sessions. It should not be shared outside
  192. // process. It is confusingly referred to as SessionID by the gliderlabs/ssh
  193. // library.
  194. idH string
  195. connID string // ID that's shared with control
  196. // anyPasswordIsOkay is whether the client is authorized but has requested
  197. // password-based auth to work around their buggy SSH client. When set, we
  198. // accept any password in the PasswordHandler.
  199. anyPasswordIsOkay bool // set by NoClientAuthCallback
  200. action0 *tailcfg.SSHAction // set by doPolicyAuth; first matching action
  201. currentAction *tailcfg.SSHAction // set by doPolicyAuth, updated by resolveNextAction
  202. finalAction *tailcfg.SSHAction // set by doPolicyAuth or resolveNextAction
  203. finalActionErr error // set by doPolicyAuth or resolveNextAction
  204. info *sshConnInfo // set by setInfo
  205. localUser *userMeta // set by doPolicyAuth
  206. userGroupIDs []string // set by doPolicyAuth
  207. pubKey gossh.PublicKey // set by doPolicyAuth
  208. // mu protects the following fields.
  209. //
  210. // srv.mu should be acquired prior to mu.
  211. // It is safe to just acquire mu, but unsafe to
  212. // acquire mu and then srv.mu.
  213. mu sync.Mutex // protects the following
  214. sessions []*sshSession
  215. }
  216. func (c *conn) logf(format string, args ...any) {
  217. format = fmt.Sprintf("%v: %v", c.connID, format)
  218. c.srv.logf(format, args...)
  219. }
  220. func (c *conn) vlogf(format string, args ...any) {
  221. if sshVerboseLogging() {
  222. c.logf(format, args...)
  223. }
  224. }
  225. // isAuthorized walks through the action chain and returns nil if the connection
  226. // is authorized. If the connection is not authorized, it returns
  227. // gossh.ErrDenied. If the action chain resolution fails, it returns the
  228. // resolution error.
  229. func (c *conn) isAuthorized(ctx ssh.Context) error {
  230. action := c.currentAction
  231. for {
  232. if action.Accept {
  233. if c.pubKey != nil {
  234. metricPublicKeyAccepts.Add(1)
  235. }
  236. return nil
  237. }
  238. if action.Reject || action.HoldAndDelegate == "" {
  239. return gossh.ErrDenied
  240. }
  241. var err error
  242. action, err = c.resolveNextAction(ctx)
  243. if err != nil {
  244. return err
  245. }
  246. if action.Message != "" {
  247. if err := ctx.SendAuthBanner(action.Message); err != nil {
  248. return err
  249. }
  250. }
  251. }
  252. }
  253. // errPubKeyRequired is returned by NoClientAuthCallback to make the client
  254. // resort to public-key auth; not user visible.
  255. var errPubKeyRequired = errors.New("ssh publickey required")
  256. // NoClientAuthCallback implements gossh.NoClientAuthCallback and is called by
  257. // the ssh.Server when the client first connects with the "none"
  258. // authentication method.
  259. //
  260. // It is responsible for continuing policy evaluation from BannerCallback (or
  261. // starting it afresh). It returns an error if the policy evaluation fails, or
  262. // if the decision is "reject"
  263. //
  264. // It either returns nil (accept) or errPubKeyRequired or gossh.ErrDenied
  265. // (reject). The errors may be wrapped.
  266. func (c *conn) NoClientAuthCallback(ctx ssh.Context) error {
  267. if c.insecureSkipTailscaleAuth {
  268. return nil
  269. }
  270. if err := c.doPolicyAuth(ctx, nil /* no pub key */); err != nil {
  271. return err
  272. }
  273. if err := c.isAuthorized(ctx); err != nil {
  274. return err
  275. }
  276. // Let users specify a username ending in +password to force password auth.
  277. // This exists for buggy SSH clients that get confused by success from
  278. // "none" auth.
  279. if strings.HasSuffix(ctx.User(), forcePasswordSuffix) {
  280. c.anyPasswordIsOkay = true
  281. return errors.New("any password please") // not shown to users
  282. }
  283. return nil
  284. }
  285. func (c *conn) nextAuthMethodCallback(cm gossh.ConnMetadata, prevErrors []error) (nextMethod []string) {
  286. switch {
  287. case c.anyPasswordIsOkay:
  288. nextMethod = append(nextMethod, "password")
  289. case len(prevErrors) > 0 && prevErrors[len(prevErrors)-1] == errPubKeyRequired:
  290. nextMethod = append(nextMethod, "publickey")
  291. }
  292. // The fake "tailscale" method is always appended to next so OpenSSH renders
  293. // that in parens as the final failure. (It also shows up in "ssh -v", etc)
  294. nextMethod = append(nextMethod, "tailscale")
  295. return
  296. }
  297. // fakePasswordHandler is our implementation of the PasswordHandler hook that
  298. // checks whether the user's password is correct. But we don't actually use
  299. // passwords. This exists only for when the user's username ends in "+password"
  300. // to signal that their SSH client is buggy and gets confused by auth type
  301. // "none" succeeding and they want our SSH server to require a dummy password
  302. // prompt instead. We then accept any password since we've already authenticated
  303. // & authorized them.
  304. func (c *conn) fakePasswordHandler(ctx ssh.Context, password string) bool {
  305. return c.anyPasswordIsOkay
  306. }
  307. // PublicKeyHandler implements ssh.PublicKeyHandler is called by the
  308. // ssh.Server when the client presents a public key.
  309. func (c *conn) PublicKeyHandler(ctx ssh.Context, pubKey ssh.PublicKey) error {
  310. if err := c.doPolicyAuth(ctx, pubKey); err != nil {
  311. // TODO(maisem/bradfitz): surface the error here.
  312. c.logf("rejecting SSH public key %s: %v", bytes.TrimSpace(gossh.MarshalAuthorizedKey(pubKey)), err)
  313. return err
  314. }
  315. if err := c.isAuthorized(ctx); err != nil {
  316. return err
  317. }
  318. c.logf("accepting SSH public key %s", bytes.TrimSpace(gossh.MarshalAuthorizedKey(pubKey)))
  319. return nil
  320. }
  321. // doPolicyAuth verifies that conn can proceed with the specified (optional)
  322. // pubKey. It returns nil if the matching policy action is Accept or
  323. // HoldAndDelegate. If pubKey is nil, there was no policy match but there is a
  324. // policy that might match a public key it returns errPubKeyRequired. Otherwise,
  325. // it returns gossh.ErrDenied.
  326. func (c *conn) doPolicyAuth(ctx ssh.Context, pubKey ssh.PublicKey) error {
  327. if err := c.setInfo(ctx); err != nil {
  328. c.logf("failed to get conninfo: %v", err)
  329. return gossh.ErrDenied
  330. }
  331. a, localUser, err := c.evaluatePolicy(pubKey)
  332. if err != nil {
  333. if pubKey == nil && c.havePubKeyPolicy() {
  334. return errPubKeyRequired
  335. }
  336. return fmt.Errorf("%w: %v", gossh.ErrDenied, err)
  337. }
  338. c.action0 = a
  339. c.currentAction = a
  340. c.pubKey = pubKey
  341. if a.Message != "" {
  342. if err := ctx.SendAuthBanner(a.Message); err != nil {
  343. return fmt.Errorf("SendBanner: %w", err)
  344. }
  345. }
  346. if a.Accept || a.HoldAndDelegate != "" {
  347. if a.Accept {
  348. c.finalAction = a
  349. }
  350. lu, err := userLookup(localUser)
  351. if err != nil {
  352. c.logf("failed to look up %v: %v", localUser, err)
  353. ctx.SendAuthBanner(fmt.Sprintf("failed to look up %v\r\n", localUser))
  354. return err
  355. }
  356. gids, err := lu.GroupIds()
  357. if err != nil {
  358. c.logf("failed to look up local user's group IDs: %v", err)
  359. return err
  360. }
  361. c.userGroupIDs = gids
  362. c.localUser = lu
  363. return nil
  364. }
  365. if a.Reject {
  366. c.finalAction = a
  367. return gossh.ErrDenied
  368. }
  369. // Shouldn't get here, but:
  370. return gossh.ErrDenied
  371. }
  372. // ServerConfig implements ssh.ServerConfigCallback.
  373. func (c *conn) ServerConfig(ctx ssh.Context) *gossh.ServerConfig {
  374. return &gossh.ServerConfig{
  375. NoClientAuth: true, // required for the NoClientAuthCallback to run
  376. NextAuthMethodCallback: c.nextAuthMethodCallback,
  377. }
  378. }
  379. func (srv *server) newConn() (*conn, error) {
  380. srv.mu.Lock()
  381. if srv.shutdownCalled {
  382. srv.mu.Unlock()
  383. // Stop accepting new connections.
  384. // Connections in the auth phase are handled in handleConnPostSSHAuth.
  385. // Existing sessions are terminated by Shutdown.
  386. return nil, gossh.ErrDenied
  387. }
  388. srv.mu.Unlock()
  389. c := &conn{srv: srv}
  390. now := srv.now()
  391. c.connID = fmt.Sprintf("ssh-conn-%s-%02x", now.UTC().Format("20060102T150405"), randBytes(5))
  392. fwdHandler := &ssh.ForwardedTCPHandler{}
  393. c.Server = &ssh.Server{
  394. Version: "Tailscale",
  395. ServerConfigCallback: c.ServerConfig,
  396. NoClientAuthHandler: c.NoClientAuthCallback,
  397. PublicKeyHandler: c.PublicKeyHandler,
  398. PasswordHandler: c.fakePasswordHandler,
  399. Handler: c.handleSessionPostSSHAuth,
  400. LocalPortForwardingCallback: c.mayForwardLocalPortTo,
  401. ReversePortForwardingCallback: c.mayReversePortForwardTo,
  402. SubsystemHandlers: map[string]ssh.SubsystemHandler{
  403. "sftp": c.handleSessionPostSSHAuth,
  404. },
  405. // Note: the direct-tcpip channel handler and LocalPortForwardingCallback
  406. // only adds support for forwarding ports from the local machine.
  407. // TODO(maisem/bradfitz): add remote port forwarding support.
  408. ChannelHandlers: map[string]ssh.ChannelHandler{
  409. "direct-tcpip": ssh.DirectTCPIPHandler,
  410. },
  411. RequestHandlers: map[string]ssh.RequestHandler{
  412. "tcpip-forward": fwdHandler.HandleSSHRequest,
  413. "cancel-tcpip-forward": fwdHandler.HandleSSHRequest,
  414. },
  415. }
  416. ss := c.Server
  417. for k, v := range ssh.DefaultRequestHandlers {
  418. ss.RequestHandlers[k] = v
  419. }
  420. for k, v := range ssh.DefaultChannelHandlers {
  421. ss.ChannelHandlers[k] = v
  422. }
  423. for k, v := range ssh.DefaultSubsystemHandlers {
  424. ss.SubsystemHandlers[k] = v
  425. }
  426. keys, err := srv.lb.GetSSH_HostKeys()
  427. if err != nil {
  428. return nil, err
  429. }
  430. for _, signer := range keys {
  431. ss.AddHostKey(signer)
  432. }
  433. return c, nil
  434. }
  435. // mayReversePortPortForwardTo reports whether the ctx should be allowed to port forward
  436. // to the specified host and port.
  437. // TODO(bradfitz/maisem): should we have more checks on host/port?
  438. func (c *conn) mayReversePortForwardTo(ctx ssh.Context, destinationHost string, destinationPort uint32) bool {
  439. if sshDisableForwarding() {
  440. return false
  441. }
  442. if c.finalAction != nil && c.finalAction.AllowRemotePortForwarding {
  443. metricRemotePortForward.Add(1)
  444. return true
  445. }
  446. return false
  447. }
  448. // mayForwardLocalPortTo reports whether the ctx should be allowed to port forward
  449. // to the specified host and port.
  450. // TODO(bradfitz/maisem): should we have more checks on host/port?
  451. func (c *conn) mayForwardLocalPortTo(ctx ssh.Context, destinationHost string, destinationPort uint32) bool {
  452. if sshDisableForwarding() {
  453. return false
  454. }
  455. if c.finalAction != nil && c.finalAction.AllowLocalPortForwarding {
  456. metricLocalPortForward.Add(1)
  457. return true
  458. }
  459. return false
  460. }
  461. // havePubKeyPolicy reports whether any policy rule may provide access by means
  462. // of a ssh.PublicKey.
  463. func (c *conn) havePubKeyPolicy() bool {
  464. if c.info == nil {
  465. panic("havePubKeyPolicy called before setInfo")
  466. }
  467. // Is there any rule that looks like it'd require a public key for this
  468. // sshUser?
  469. pol, ok := c.sshPolicy()
  470. if !ok {
  471. return false
  472. }
  473. for _, r := range pol.Rules {
  474. if c.ruleExpired(r) {
  475. continue
  476. }
  477. if mapLocalUser(r.SSHUsers, c.info.sshUser) == "" {
  478. continue
  479. }
  480. for _, p := range r.Principals {
  481. if len(p.PubKeys) > 0 && c.principalMatchesTailscaleIdentity(p) {
  482. return true
  483. }
  484. }
  485. }
  486. return false
  487. }
  488. // sshPolicy returns the SSHPolicy for current node.
  489. // If there is no SSHPolicy in the netmap, it returns a debugPolicy
  490. // if one is defined.
  491. func (c *conn) sshPolicy() (_ *tailcfg.SSHPolicy, ok bool) {
  492. lb := c.srv.lb
  493. if !lb.ShouldRunSSH() {
  494. return nil, false
  495. }
  496. nm := lb.NetMap()
  497. if nm == nil {
  498. return nil, false
  499. }
  500. if pol := nm.SSHPolicy; pol != nil && !envknob.SSHIgnoreTailnetPolicy() {
  501. return pol, true
  502. }
  503. debugPolicyFile := envknob.SSHPolicyFile()
  504. if debugPolicyFile != "" {
  505. c.logf("reading debug SSH policy file: %v", debugPolicyFile)
  506. f, err := os.ReadFile(debugPolicyFile)
  507. if err != nil {
  508. c.logf("error reading debug SSH policy file: %v", err)
  509. return nil, false
  510. }
  511. p := new(tailcfg.SSHPolicy)
  512. if err := json.Unmarshal(f, p); err != nil {
  513. c.logf("invalid JSON in %v: %v", debugPolicyFile, err)
  514. return nil, false
  515. }
  516. return p, true
  517. }
  518. return nil, false
  519. }
  520. func toIPPort(a net.Addr) (ipp netip.AddrPort) {
  521. ta, ok := a.(*net.TCPAddr)
  522. if !ok {
  523. return
  524. }
  525. tanetaddr, ok := netip.AddrFromSlice(ta.IP)
  526. if !ok {
  527. return
  528. }
  529. return netip.AddrPortFrom(tanetaddr.Unmap(), uint16(ta.Port))
  530. }
  531. // connInfo returns a populated sshConnInfo from the provided arguments,
  532. // validating only that they represent a known Tailscale identity.
  533. func (c *conn) setInfo(ctx ssh.Context) error {
  534. if c.info != nil {
  535. return nil
  536. }
  537. ci := &sshConnInfo{
  538. sshUser: strings.TrimSuffix(ctx.User(), forcePasswordSuffix),
  539. src: toIPPort(ctx.RemoteAddr()),
  540. dst: toIPPort(ctx.LocalAddr()),
  541. }
  542. if !tsaddr.IsTailscaleIP(ci.dst.Addr()) {
  543. return fmt.Errorf("tailssh: rejecting non-Tailscale local address %v", ci.dst)
  544. }
  545. if !tsaddr.IsTailscaleIP(ci.src.Addr()) {
  546. return fmt.Errorf("tailssh: rejecting non-Tailscale remote address %v", ci.src)
  547. }
  548. node, uprof, ok := c.srv.lb.WhoIs(ci.src)
  549. if !ok {
  550. return fmt.Errorf("unknown Tailscale identity from src %v", ci.src)
  551. }
  552. ci.node = node
  553. ci.uprof = uprof
  554. c.idH = ctx.SessionID()
  555. c.info = ci
  556. c.logf("handling conn: %v", ci.String())
  557. return nil
  558. }
  559. // evaluatePolicy returns the SSHAction and localUser after evaluating
  560. // the SSHPolicy for this conn. The pubKey may be nil for "none" auth.
  561. func (c *conn) evaluatePolicy(pubKey gossh.PublicKey) (_ *tailcfg.SSHAction, localUser string, _ error) {
  562. pol, ok := c.sshPolicy()
  563. if !ok {
  564. return nil, "", fmt.Errorf("tailssh: rejecting connection; no SSH policy")
  565. }
  566. a, localUser, ok := c.evalSSHPolicy(pol, pubKey)
  567. if !ok {
  568. return nil, "", fmt.Errorf("tailssh: rejecting connection; no matching policy")
  569. }
  570. return a, localUser, nil
  571. }
  572. // pubKeyCacheEntry is the cache value for an HTTPS URL of public keys (like
  573. // "https://github.com/foo.keys")
  574. type pubKeyCacheEntry struct {
  575. lines []string
  576. etag string // if sent by server
  577. at time.Time
  578. }
  579. const (
  580. pubKeyCacheDuration = time.Minute // how long to cache non-empty public keys
  581. pubKeyCacheEmptyDuration = 15 * time.Second // how long to cache empty responses
  582. )
  583. func (srv *server) fetchPublicKeysURLCached(url string) (ce pubKeyCacheEntry, ok bool) {
  584. srv.mu.Lock()
  585. defer srv.mu.Unlock()
  586. // Mostly don't care about the size of this cache. Clean rarely.
  587. if m := srv.fetchPublicKeysCache; len(m) > 50 {
  588. tooOld := srv.now().Add(pubKeyCacheDuration * 10)
  589. for k, ce := range m {
  590. if ce.at.Before(tooOld) {
  591. delete(m, k)
  592. }
  593. }
  594. }
  595. ce, ok = srv.fetchPublicKeysCache[url]
  596. if !ok {
  597. return ce, false
  598. }
  599. maxAge := pubKeyCacheDuration
  600. if len(ce.lines) == 0 {
  601. maxAge = pubKeyCacheEmptyDuration
  602. }
  603. return ce, srv.now().Sub(ce.at) < maxAge
  604. }
  605. func (srv *server) pubKeyClient() *http.Client {
  606. if srv.pubKeyHTTPClient != nil {
  607. return srv.pubKeyHTTPClient
  608. }
  609. return http.DefaultClient
  610. }
  611. // fetchPublicKeysURL fetches the public keys from a URL. The strings are in the
  612. // the typical public key "type base64-string [comment]" format seen at e.g.
  613. // https://github.com/USER.keys
  614. func (srv *server) fetchPublicKeysURL(url string) ([]string, error) {
  615. if !strings.HasPrefix(url, "https://") {
  616. return nil, errors.New("invalid URL scheme")
  617. }
  618. ce, ok := srv.fetchPublicKeysURLCached(url)
  619. if ok {
  620. return ce.lines, nil
  621. }
  622. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  623. defer cancel()
  624. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  625. if err != nil {
  626. return nil, err
  627. }
  628. if ce.etag != "" {
  629. req.Header.Add("If-None-Match", ce.etag)
  630. }
  631. res, err := srv.pubKeyClient().Do(req)
  632. if err != nil {
  633. return nil, err
  634. }
  635. defer res.Body.Close()
  636. var lines []string
  637. var etag string
  638. switch res.StatusCode {
  639. default:
  640. err = fmt.Errorf("unexpected status %v", res.Status)
  641. srv.logf("fetching public keys from %s: %v", url, err)
  642. case http.StatusNotModified:
  643. lines = ce.lines
  644. etag = ce.etag
  645. case http.StatusOK:
  646. var all []byte
  647. all, err = io.ReadAll(io.LimitReader(res.Body, 4<<10))
  648. if s := strings.TrimSpace(string(all)); s != "" {
  649. lines = strings.Split(s, "\n")
  650. }
  651. etag = res.Header.Get("Etag")
  652. }
  653. srv.mu.Lock()
  654. defer srv.mu.Unlock()
  655. mak.Set(&srv.fetchPublicKeysCache, url, pubKeyCacheEntry{
  656. at: srv.now(),
  657. lines: lines,
  658. etag: etag,
  659. })
  660. return lines, err
  661. }
  662. // handleSessionPostSSHAuth runs an SSH session after the SSH-level authentication,
  663. // but not necessarily before all the Tailscale-level extra verification has
  664. // completed. It also handles SFTP requests.
  665. func (c *conn) handleSessionPostSSHAuth(s ssh.Session) {
  666. // Do this check after auth, but before starting the session.
  667. switch s.Subsystem() {
  668. case "sftp":
  669. if sshDisableSFTP() {
  670. fmt.Fprintf(s.Stderr(), "sftp disabled\r\n")
  671. s.Exit(1)
  672. return
  673. }
  674. metricSFTP.Add(1)
  675. case "":
  676. // Regular SSH session.
  677. default:
  678. fmt.Fprintf(s.Stderr(), "Unsupported subsystem %q\r\n", s.Subsystem())
  679. s.Exit(1)
  680. return
  681. }
  682. ss := c.newSSHSession(s)
  683. ss.logf("handling new SSH connection from %v (%v) to ssh-user %q", c.info.uprof.LoginName, c.info.src.Addr(), c.localUser.Username)
  684. ss.logf("access granted to %v as ssh-user %q", c.info.uprof.LoginName, c.localUser.Username)
  685. ss.run()
  686. }
  687. // resolveNextAction starts at c.currentAction and makes it way through the
  688. // action chain one step at a time. An action without a HoldAndDelegate is
  689. // considered the final action. Once a final action is reached, this function
  690. // will keep returning that action. It updates c.currentAction to the next
  691. // action in the chain. When the final action is reached, it also sets
  692. // c.finalAction to the final action.
  693. func (c *conn) resolveNextAction(sctx ssh.Context) (action *tailcfg.SSHAction, err error) {
  694. if c.finalAction != nil || c.finalActionErr != nil {
  695. return c.finalAction, c.finalActionErr
  696. }
  697. defer func() {
  698. if action != nil {
  699. c.currentAction = action
  700. if action.Accept || action.Reject {
  701. c.finalAction = action
  702. }
  703. }
  704. if err != nil {
  705. c.finalActionErr = err
  706. }
  707. }()
  708. ctx, cancel := context.WithCancel(sctx)
  709. defer cancel()
  710. // Loop processing/fetching Actions until one reaches a
  711. // terminal state (Accept, Reject, or invalid Action), or
  712. // until fetchSSHAction times out due to the context being
  713. // done (client disconnect) or its 30 minute timeout passes.
  714. // (Which is a long time for somebody to see login
  715. // instructions and go to a URL to do something.)
  716. action = c.currentAction
  717. if action.Accept || action.Reject {
  718. if action.Reject {
  719. metricTerminalReject.Add(1)
  720. } else {
  721. metricTerminalAccept.Add(1)
  722. }
  723. return action, nil
  724. }
  725. url := action.HoldAndDelegate
  726. if url == "" {
  727. metricTerminalMalformed.Add(1)
  728. return nil, errors.New("reached Action that lacked Accept, Reject, and HoldAndDelegate")
  729. }
  730. metricHolds.Add(1)
  731. url = c.expandDelegateURLLocked(url)
  732. nextAction, err := c.fetchSSHAction(ctx, url)
  733. if err != nil {
  734. metricTerminalFetchError.Add(1)
  735. return nil, fmt.Errorf("fetching SSHAction from %s: %w", url, err)
  736. }
  737. return nextAction, nil
  738. }
  739. func (c *conn) expandDelegateURLLocked(actionURL string) string {
  740. nm := c.srv.lb.NetMap()
  741. ci := c.info
  742. lu := c.localUser
  743. var dstNodeID string
  744. if nm != nil {
  745. dstNodeID = fmt.Sprint(int64(nm.SelfNode.ID()))
  746. }
  747. return strings.NewReplacer(
  748. "$SRC_NODE_IP", url.QueryEscape(ci.src.Addr().String()),
  749. "$SRC_NODE_ID", fmt.Sprint(int64(ci.node.ID())),
  750. "$DST_NODE_IP", url.QueryEscape(ci.dst.Addr().String()),
  751. "$DST_NODE_ID", dstNodeID,
  752. "$SSH_USER", url.QueryEscape(ci.sshUser),
  753. "$LOCAL_USER", url.QueryEscape(lu.Username),
  754. ).Replace(actionURL)
  755. }
  756. func (c *conn) expandPublicKeyURL(pubKeyURL string) string {
  757. if !strings.Contains(pubKeyURL, "$") {
  758. return pubKeyURL
  759. }
  760. loginName := c.info.uprof.LoginName
  761. localPart, _, _ := strings.Cut(loginName, "@")
  762. return strings.NewReplacer(
  763. "$LOGINNAME_EMAIL", loginName,
  764. "$LOGINNAME_LOCALPART", localPart,
  765. ).Replace(pubKeyURL)
  766. }
  767. // sshSession is an accepted Tailscale SSH session.
  768. type sshSession struct {
  769. ssh.Session
  770. sharedID string // ID that's shared with control
  771. logf logger.Logf
  772. ctx context.Context
  773. cancelCtx context.CancelCauseFunc
  774. conn *conn
  775. agentListener net.Listener // non-nil if agent-forwarding requested+allowed
  776. // initialized by launchProcess:
  777. cmd *exec.Cmd
  778. wrStdin io.WriteCloser
  779. rdStdout io.ReadCloser
  780. rdStderr io.ReadCloser // rdStderr is nil for pty sessions
  781. ptyReq *ssh.Pty // non-nil for pty sessions
  782. // childPipes is a list of pipes that need to be closed when the process exits.
  783. // For pty sessions, this is the tty fd.
  784. // For non-pty sessions, this is the stdin, stdout, stderr fds.
  785. childPipes []io.Closer
  786. // We use this sync.Once to ensure that we only terminate the process once,
  787. // either it exits itself or is terminated
  788. exitOnce sync.Once
  789. }
  790. func (ss *sshSession) vlogf(format string, args ...any) {
  791. if sshVerboseLogging() {
  792. ss.logf(format, args...)
  793. }
  794. }
  795. func (c *conn) newSSHSession(s ssh.Session) *sshSession {
  796. sharedID := fmt.Sprintf("sess-%s-%02x", c.srv.now().UTC().Format("20060102T150405"), randBytes(5))
  797. c.logf("starting session: %v", sharedID)
  798. ctx, cancel := context.WithCancelCause(s.Context())
  799. return &sshSession{
  800. Session: s,
  801. sharedID: sharedID,
  802. ctx: ctx,
  803. cancelCtx: cancel,
  804. conn: c,
  805. logf: logger.WithPrefix(c.srv.logf, "ssh-session("+sharedID+"): "),
  806. }
  807. }
  808. // isStillValid reports whether the conn is still valid.
  809. func (c *conn) isStillValid() bool {
  810. a, localUser, err := c.evaluatePolicy(c.pubKey)
  811. c.vlogf("stillValid: %+v %v %v", a, localUser, err)
  812. if err != nil {
  813. return false
  814. }
  815. if !a.Accept && a.HoldAndDelegate == "" {
  816. return false
  817. }
  818. return c.localUser.Username == localUser
  819. }
  820. // checkStillValid checks that the conn is still valid per the latest SSHPolicy.
  821. // If not, it terminates all sessions associated with the conn.
  822. func (c *conn) checkStillValid() {
  823. if c.isStillValid() {
  824. return
  825. }
  826. metricPolicyChangeKick.Add(1)
  827. c.logf("session no longer valid per new SSH policy; closing")
  828. c.mu.Lock()
  829. defer c.mu.Unlock()
  830. for _, s := range c.sessions {
  831. s.cancelCtx(userVisibleError{
  832. fmt.Sprintf("Access revoked.\r\n"),
  833. context.Canceled,
  834. })
  835. }
  836. }
  837. func (c *conn) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHAction, error) {
  838. ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
  839. defer cancel()
  840. bo := backoff.NewBackoff("fetch-ssh-action", c.logf, 10*time.Second)
  841. for {
  842. if err := ctx.Err(); err != nil {
  843. return nil, err
  844. }
  845. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  846. if err != nil {
  847. return nil, err
  848. }
  849. res, err := c.srv.lb.DoNoiseRequest(req)
  850. if err != nil {
  851. bo.BackOff(ctx, err)
  852. continue
  853. }
  854. if res.StatusCode != 200 {
  855. body, _ := io.ReadAll(res.Body)
  856. res.Body.Close()
  857. if len(body) > 1<<10 {
  858. body = body[:1<<10]
  859. }
  860. c.logf("fetch of %v: %s, %s", url, res.Status, body)
  861. bo.BackOff(ctx, fmt.Errorf("unexpected status: %v", res.Status))
  862. continue
  863. }
  864. a := new(tailcfg.SSHAction)
  865. err = json.NewDecoder(res.Body).Decode(a)
  866. res.Body.Close()
  867. if err != nil {
  868. c.logf("invalid next SSHAction JSON from %v: %v", url, err)
  869. bo.BackOff(ctx, err)
  870. continue
  871. }
  872. return a, nil
  873. }
  874. }
  875. // killProcessOnContextDone waits for ss.ctx to be done and kills the process,
  876. // unless the process has already exited.
  877. func (ss *sshSession) killProcessOnContextDone() {
  878. <-ss.ctx.Done()
  879. // Either the process has already exited, in which case this does nothing.
  880. // Or, the process is still running in which case this will kill it.
  881. ss.exitOnce.Do(func() {
  882. err := context.Cause(ss.ctx)
  883. if serr, ok := err.(SSHTerminationError); ok {
  884. msg := serr.SSHTerminationMessage()
  885. if msg != "" {
  886. io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n")
  887. }
  888. }
  889. ss.logf("terminating SSH session from %v: %v", ss.conn.info.src.Addr(), err)
  890. // We don't need to Process.Wait here, sshSession.run() does
  891. // the waiting regardless of termination reason.
  892. // TODO(maisem): should this be a SIGTERM followed by a SIGKILL?
  893. ss.cmd.Process.Kill()
  894. })
  895. }
  896. // attachSession registers ss as an active session.
  897. func (c *conn) attachSession(ss *sshSession) {
  898. c.srv.sessionWaitGroup.Add(1)
  899. if ss.sharedID == "" {
  900. panic("empty sharedID")
  901. }
  902. c.mu.Lock()
  903. defer c.mu.Unlock()
  904. c.sessions = append(c.sessions, ss)
  905. }
  906. // detachSession unregisters s from the list of active sessions.
  907. func (c *conn) detachSession(ss *sshSession) {
  908. defer c.srv.sessionWaitGroup.Done()
  909. c.mu.Lock()
  910. defer c.mu.Unlock()
  911. for i, s := range c.sessions {
  912. if s == ss {
  913. c.sessions = append(c.sessions[:i], c.sessions[i+1:]...)
  914. break
  915. }
  916. }
  917. }
  918. var errSessionDone = errors.New("session is done")
  919. // handleSSHAgentForwarding starts a Unix socket listener and in the background
  920. // forwards agent connections between the listener and the ssh.Session.
  921. // On success, it assigns ss.agentListener.
  922. func (ss *sshSession) handleSSHAgentForwarding(s ssh.Session, lu *userMeta) error {
  923. if !ssh.AgentRequested(ss) || !ss.conn.finalAction.AllowAgentForwarding {
  924. return nil
  925. }
  926. if sshDisableForwarding() {
  927. // TODO(bradfitz): or do we want to return an error here instead so the user
  928. // gets an error if they ran with ssh -A? But for now we just silently
  929. // don't work, like the condition above.
  930. return nil
  931. }
  932. ss.logf("ssh: agent forwarding requested")
  933. ln, err := ssh.NewAgentListener()
  934. if err != nil {
  935. return err
  936. }
  937. defer func() {
  938. if err != nil && ln != nil {
  939. ln.Close()
  940. }
  941. }()
  942. uid, err := strconv.ParseUint(lu.Uid, 10, 32)
  943. if err != nil {
  944. return err
  945. }
  946. gid, err := strconv.ParseUint(lu.Gid, 10, 32)
  947. if err != nil {
  948. return err
  949. }
  950. socket := ln.Addr().String()
  951. dir := filepath.Dir(socket)
  952. // Make sure the socket is accessible only by the user.
  953. if err := os.Chmod(socket, 0600); err != nil {
  954. return err
  955. }
  956. if err := os.Chown(socket, int(uid), int(gid)); err != nil {
  957. return err
  958. }
  959. // Make sure the dir is also accessible.
  960. if err := os.Chmod(dir, 0755); err != nil {
  961. return err
  962. }
  963. go ssh.ForwardAgentConnections(ln, s)
  964. ss.agentListener = ln
  965. return nil
  966. }
  967. // run is the entrypoint for a newly accepted SSH session.
  968. //
  969. // It handles ss once it's been accepted and determined
  970. // that it should run.
  971. func (ss *sshSession) run() {
  972. metricActiveSessions.Add(1)
  973. defer metricActiveSessions.Add(-1)
  974. defer ss.cancelCtx(errSessionDone)
  975. if attached := ss.conn.srv.attachSessionToConnIfNotShutdown(ss); !attached {
  976. fmt.Fprintf(ss, "Tailscale SSH is shutting down\r\n")
  977. ss.Exit(1)
  978. return
  979. }
  980. defer ss.conn.detachSession(ss)
  981. lu := ss.conn.localUser
  982. logf := ss.logf
  983. if ss.conn.finalAction.SessionDuration != 0 {
  984. t := time.AfterFunc(ss.conn.finalAction.SessionDuration, func() {
  985. ss.cancelCtx(userVisibleError{
  986. fmt.Sprintf("Session timeout of %v elapsed.", ss.conn.finalAction.SessionDuration),
  987. context.DeadlineExceeded,
  988. })
  989. })
  990. defer t.Stop()
  991. }
  992. if euid := os.Geteuid(); euid != 0 {
  993. if lu.Uid != fmt.Sprint(euid) {
  994. ss.logf("can't switch to user %q from process euid %v", lu.Username, euid)
  995. fmt.Fprintf(ss, "can't switch user\r\n")
  996. ss.Exit(1)
  997. return
  998. }
  999. }
  1000. // Take control of the PTY so that we can configure it below.
  1001. // See https://github.com/tailscale/tailscale/issues/4146
  1002. ss.DisablePTYEmulation()
  1003. var rec *recording // or nil if disabled
  1004. if ss.Subsystem() != "sftp" {
  1005. if err := ss.handleSSHAgentForwarding(ss, lu); err != nil {
  1006. ss.logf("agent forwarding failed: %v", err)
  1007. } else if ss.agentListener != nil {
  1008. // TODO(maisem/bradfitz): add a way to close all session resources
  1009. defer ss.agentListener.Close()
  1010. }
  1011. if ss.shouldRecord() {
  1012. var err error
  1013. rec, err = ss.startNewRecording()
  1014. if err != nil {
  1015. var uve userVisibleError
  1016. if errors.As(err, &uve) {
  1017. fmt.Fprintf(ss, "%s\r\n", uve.SSHTerminationMessage())
  1018. } else {
  1019. fmt.Fprintf(ss, "can't start new recording\r\n")
  1020. }
  1021. ss.logf("startNewRecording: %v", err)
  1022. ss.Exit(1)
  1023. return
  1024. }
  1025. ss.logf("startNewRecording: <nil>")
  1026. if rec != nil {
  1027. defer rec.Close()
  1028. }
  1029. }
  1030. }
  1031. err := ss.launchProcess()
  1032. if err != nil {
  1033. logf("start failed: %v", err.Error())
  1034. if errors.Is(err, context.Canceled) {
  1035. err := context.Cause(ss.ctx)
  1036. var uve userVisibleError
  1037. if errors.As(err, &uve) {
  1038. fmt.Fprintf(ss, "%s\r\n", uve)
  1039. }
  1040. }
  1041. ss.Exit(1)
  1042. return
  1043. }
  1044. go ss.killProcessOnContextDone()
  1045. var processDone atomic.Bool
  1046. go func() {
  1047. defer ss.wrStdin.Close()
  1048. if _, err := io.Copy(rec.writer("i", ss.wrStdin), ss); err != nil {
  1049. logf("stdin copy: %v", err)
  1050. ss.cancelCtx(err)
  1051. }
  1052. }()
  1053. outputDone := make(chan struct{})
  1054. var openOutputStreams atomic.Int32
  1055. if ss.rdStderr != nil {
  1056. openOutputStreams.Store(2)
  1057. } else {
  1058. openOutputStreams.Store(1)
  1059. }
  1060. go func() {
  1061. defer ss.rdStdout.Close()
  1062. _, err := io.Copy(rec.writer("o", ss), ss.rdStdout)
  1063. if err != nil && !errors.Is(err, io.EOF) {
  1064. isErrBecauseProcessExited := processDone.Load() && errors.Is(err, syscall.EIO)
  1065. if !isErrBecauseProcessExited {
  1066. logf("stdout copy: %v, %T", err)
  1067. ss.cancelCtx(err)
  1068. }
  1069. }
  1070. if openOutputStreams.Add(-1) == 0 {
  1071. ss.CloseWrite()
  1072. close(outputDone)
  1073. }
  1074. }()
  1075. // rdStderr is nil for ptys.
  1076. if ss.rdStderr != nil {
  1077. go func() {
  1078. defer ss.rdStderr.Close()
  1079. _, err := io.Copy(ss.Stderr(), ss.rdStderr)
  1080. if err != nil {
  1081. logf("stderr copy: %v", err)
  1082. }
  1083. if openOutputStreams.Add(-1) == 0 {
  1084. ss.CloseWrite()
  1085. close(outputDone)
  1086. }
  1087. }()
  1088. }
  1089. err = ss.cmd.Wait()
  1090. processDone.Store(true)
  1091. // This will either make the SSH Termination goroutine be a no-op,
  1092. // or itself will be a no-op because the process was killed by the
  1093. // aforementioned goroutine.
  1094. ss.exitOnce.Do(func() {})
  1095. // Close the process-side of all pipes to signal the asynchronous
  1096. // io.Copy routines reading/writing from the pipes to terminate.
  1097. // Block for the io.Copy to finish before calling ss.Exit below.
  1098. closeAll(ss.childPipes...)
  1099. select {
  1100. case <-outputDone:
  1101. case <-ss.ctx.Done():
  1102. }
  1103. if err == nil {
  1104. ss.logf("Session complete")
  1105. ss.Exit(0)
  1106. return
  1107. }
  1108. if ee, ok := err.(*exec.ExitError); ok {
  1109. code := ee.ProcessState.ExitCode()
  1110. ss.logf("Wait: code=%v", code)
  1111. ss.Exit(code)
  1112. return
  1113. }
  1114. ss.logf("Wait: %v", err)
  1115. ss.Exit(1)
  1116. return
  1117. }
  1118. // recordSSHToLocalDisk is a deprecated dev knob to allow recording SSH sessions
  1119. // to local storage. It is only used if there is no recording configured by the
  1120. // coordination server. This will be removed in the future.
  1121. var recordSSHToLocalDisk = envknob.RegisterBool("TS_DEBUG_LOG_SSH")
  1122. // recorders returns the list of recorders to use for this session.
  1123. // If the final action has a non-empty list of recorders, that list is
  1124. // returned. Otherwise, the list of recorders from the initial action
  1125. // is returned.
  1126. func (ss *sshSession) recorders() ([]netip.AddrPort, *tailcfg.SSHRecorderFailureAction) {
  1127. if len(ss.conn.finalAction.Recorders) > 0 {
  1128. return ss.conn.finalAction.Recorders, ss.conn.finalAction.OnRecordingFailure
  1129. }
  1130. return ss.conn.action0.Recorders, ss.conn.action0.OnRecordingFailure
  1131. }
  1132. func (ss *sshSession) shouldRecord() bool {
  1133. recs, _ := ss.recorders()
  1134. return len(recs) > 0 || recordSSHToLocalDisk()
  1135. }
  1136. type sshConnInfo struct {
  1137. // sshUser is the requested local SSH username ("root", "alice", etc).
  1138. sshUser string
  1139. // src is the Tailscale IP and port that the connection came from.
  1140. src netip.AddrPort
  1141. // dst is the Tailscale IP and port that the connection came for.
  1142. dst netip.AddrPort
  1143. // node is srcIP's node.
  1144. node tailcfg.NodeView
  1145. // uprof is node's UserProfile.
  1146. uprof tailcfg.UserProfile
  1147. }
  1148. func (ci *sshConnInfo) String() string {
  1149. return fmt.Sprintf("%v->%v@%v", ci.src, ci.sshUser, ci.dst)
  1150. }
  1151. func (c *conn) ruleExpired(r *tailcfg.SSHRule) bool {
  1152. if r.RuleExpires == nil {
  1153. return false
  1154. }
  1155. return r.RuleExpires.Before(c.srv.now())
  1156. }
  1157. func (c *conn) evalSSHPolicy(pol *tailcfg.SSHPolicy, pubKey gossh.PublicKey) (a *tailcfg.SSHAction, localUser string, ok bool) {
  1158. for _, r := range pol.Rules {
  1159. if a, localUser, err := c.matchRule(r, pubKey); err == nil {
  1160. return a, localUser, true
  1161. }
  1162. }
  1163. return nil, "", false
  1164. }
  1165. // internal errors for testing; they don't escape to callers or logs.
  1166. var (
  1167. errNilRule = errors.New("nil rule")
  1168. errNilAction = errors.New("nil action")
  1169. errRuleExpired = errors.New("rule expired")
  1170. errPrincipalMatch = errors.New("principal didn't match")
  1171. errUserMatch = errors.New("user didn't match")
  1172. errInvalidConn = errors.New("invalid connection state")
  1173. )
  1174. func (c *conn) matchRule(r *tailcfg.SSHRule, pubKey gossh.PublicKey) (a *tailcfg.SSHAction, localUser string, err error) {
  1175. defer func() {
  1176. c.vlogf("matchRule(%+v): %v", r, err)
  1177. }()
  1178. if c == nil {
  1179. return nil, "", errInvalidConn
  1180. }
  1181. if c.info == nil {
  1182. c.logf("invalid connection state")
  1183. return nil, "", errInvalidConn
  1184. }
  1185. if r == nil {
  1186. return nil, "", errNilRule
  1187. }
  1188. if r.Action == nil {
  1189. return nil, "", errNilAction
  1190. }
  1191. if c.ruleExpired(r) {
  1192. return nil, "", errRuleExpired
  1193. }
  1194. if !r.Action.Reject {
  1195. // For all but Reject rules, SSHUsers is required.
  1196. // If SSHUsers is nil or empty, mapLocalUser will return an
  1197. // empty string anyway.
  1198. localUser = mapLocalUser(r.SSHUsers, c.info.sshUser)
  1199. if localUser == "" {
  1200. return nil, "", errUserMatch
  1201. }
  1202. }
  1203. if ok, err := c.anyPrincipalMatches(r.Principals, pubKey); err != nil {
  1204. return nil, "", err
  1205. } else if !ok {
  1206. return nil, "", errPrincipalMatch
  1207. }
  1208. return r.Action, localUser, nil
  1209. }
  1210. func mapLocalUser(ruleSSHUsers map[string]string, reqSSHUser string) (localUser string) {
  1211. v, ok := ruleSSHUsers[reqSSHUser]
  1212. if !ok {
  1213. v = ruleSSHUsers["*"]
  1214. }
  1215. if v == "=" {
  1216. return reqSSHUser
  1217. }
  1218. return v
  1219. }
  1220. func (c *conn) anyPrincipalMatches(ps []*tailcfg.SSHPrincipal, pubKey gossh.PublicKey) (bool, error) {
  1221. for _, p := range ps {
  1222. if p == nil {
  1223. continue
  1224. }
  1225. if ok, err := c.principalMatches(p, pubKey); err != nil {
  1226. return false, err
  1227. } else if ok {
  1228. return true, nil
  1229. }
  1230. }
  1231. return false, nil
  1232. }
  1233. func (c *conn) principalMatches(p *tailcfg.SSHPrincipal, pubKey gossh.PublicKey) (bool, error) {
  1234. if !c.principalMatchesTailscaleIdentity(p) {
  1235. return false, nil
  1236. }
  1237. return c.principalMatchesPubKey(p, pubKey)
  1238. }
  1239. // principalMatchesTailscaleIdentity reports whether one of p's four fields
  1240. // that match the Tailscale identity match (Node, NodeIP, UserLogin, Any).
  1241. // This function does not consider PubKeys.
  1242. func (c *conn) principalMatchesTailscaleIdentity(p *tailcfg.SSHPrincipal) bool {
  1243. ci := c.info
  1244. if p.Any {
  1245. return true
  1246. }
  1247. if !p.Node.IsZero() && ci.node.Valid() && p.Node == ci.node.StableID() {
  1248. return true
  1249. }
  1250. if p.NodeIP != "" {
  1251. if ip, _ := netip.ParseAddr(p.NodeIP); ip == ci.src.Addr() {
  1252. return true
  1253. }
  1254. }
  1255. if p.UserLogin != "" && ci.uprof.LoginName == p.UserLogin {
  1256. return true
  1257. }
  1258. return false
  1259. }
  1260. func (c *conn) principalMatchesPubKey(p *tailcfg.SSHPrincipal, clientPubKey gossh.PublicKey) (bool, error) {
  1261. if len(p.PubKeys) == 0 {
  1262. return true, nil
  1263. }
  1264. if clientPubKey == nil {
  1265. return false, nil
  1266. }
  1267. knownKeys := p.PubKeys
  1268. if len(knownKeys) == 1 && strings.HasPrefix(knownKeys[0], "https://") {
  1269. var err error
  1270. knownKeys, err = c.srv.fetchPublicKeysURL(c.expandPublicKeyURL(knownKeys[0]))
  1271. if err != nil {
  1272. return false, err
  1273. }
  1274. }
  1275. for _, knownKey := range knownKeys {
  1276. if pubKeyMatchesAuthorizedKey(clientPubKey, knownKey) {
  1277. return true, nil
  1278. }
  1279. }
  1280. return false, nil
  1281. }
  1282. func pubKeyMatchesAuthorizedKey(pubKey ssh.PublicKey, wantKey string) bool {
  1283. wantKeyType, rest, ok := strings.Cut(wantKey, " ")
  1284. if !ok {
  1285. return false
  1286. }
  1287. if pubKey.Type() != wantKeyType {
  1288. return false
  1289. }
  1290. wantKeyB64, _, _ := strings.Cut(rest, " ")
  1291. wantKeyData, _ := base64.StdEncoding.DecodeString(wantKeyB64)
  1292. return len(wantKeyData) > 0 && bytes.Equal(pubKey.Marshal(), wantKeyData)
  1293. }
  1294. func randBytes(n int) []byte {
  1295. b := make([]byte, n)
  1296. if _, err := rand.Read(b); err != nil {
  1297. panic(err)
  1298. }
  1299. return b
  1300. }
  1301. // CastHeader is the header of an asciinema file.
  1302. type CastHeader struct {
  1303. // Version is the asciinema file format version.
  1304. Version int `json:"version"`
  1305. // Width is the terminal width in characters.
  1306. // It is non-zero for Pty sessions.
  1307. Width int `json:"width"`
  1308. // Height is the terminal height in characters.
  1309. // It is non-zero for Pty sessions.
  1310. Height int `json:"height"`
  1311. // Timestamp is the unix timestamp of when the recording started.
  1312. Timestamp int64 `json:"timestamp"`
  1313. // Env is the environment variables of the session.
  1314. // Only "TERM" is set (2023-03-22).
  1315. Env map[string]string `json:"env"`
  1316. // Command is the command that was executed.
  1317. // Typically empty for shell sessions.
  1318. Command string `json:"command,omitempty"`
  1319. // Tailscale-specific fields:
  1320. // SrcNode is the FQDN of the node originating the connection.
  1321. // It is also the MagicDNS name for the node.
  1322. // It does not have a trailing dot.
  1323. // e.g. "host.tail-scale.ts.net"
  1324. SrcNode string `json:"srcNode"`
  1325. // SrcNodeID is the node ID of the node originating the connection.
  1326. SrcNodeID tailcfg.StableNodeID `json:"srcNodeID"`
  1327. // SrcNodeTags is the list of tags on the node originating the connection (if any).
  1328. SrcNodeTags []string `json:"srcNodeTags,omitempty"`
  1329. // SrcNodeUserID is the user ID of the node originating the connection (if not tagged).
  1330. SrcNodeUserID tailcfg.UserID `json:"srcNodeUserID,omitempty"` // if not tagged
  1331. // SrcNodeUser is the LoginName of the node originating the connection (if not tagged).
  1332. SrcNodeUser string `json:"srcNodeUser,omitempty"`
  1333. // SSHUser is the username as presented by the client.
  1334. SSHUser string `json:"sshUser"` // as presented by the client
  1335. // LocalUser is the effective username on the server.
  1336. LocalUser string `json:"localUser"`
  1337. // ConnectionID uniquely identifies a connection made to the SSH server.
  1338. // It may be shared across multiple sessions over the same connection in
  1339. // case of SSH multiplexing.
  1340. ConnectionID string `json:"connectionID"`
  1341. }
  1342. // sessionRecordingClient returns an http.Client that uses srv.lb.Dialer() to
  1343. // dial connections. This is used to make requests to the session recording
  1344. // server to upload session recordings.
  1345. // It uses the provided dialCtx to dial connections, and limits a single dial
  1346. // to 5 seconds.
  1347. func (ss *sshSession) sessionRecordingClient(dialCtx context.Context) (*http.Client, error) {
  1348. dialer := ss.conn.srv.lb.Dialer()
  1349. if dialer == nil {
  1350. return nil, errors.New("no peer API transport")
  1351. }
  1352. tr := dialer.PeerAPITransport().Clone()
  1353. dialContextFn := tr.DialContext
  1354. tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  1355. perAttemptCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
  1356. defer cancel()
  1357. go func() {
  1358. select {
  1359. case <-perAttemptCtx.Done():
  1360. case <-dialCtx.Done():
  1361. cancel()
  1362. }
  1363. }()
  1364. return dialContextFn(perAttemptCtx, network, addr)
  1365. }
  1366. return &http.Client{
  1367. Transport: tr,
  1368. }, nil
  1369. }
  1370. // connectToRecorder connects to the recorder at any of the provided addresses.
  1371. // It returns the first successful response, or a multierr if all attempts fail.
  1372. //
  1373. // On success, it returns a WriteCloser that can be used to upload the
  1374. // recording, and a channel that will be sent an error (or nil) when the upload
  1375. // fails or completes.
  1376. //
  1377. // In both cases, a slice of SSHRecordingAttempts is returned which detail the
  1378. // attempted recorder IP and the error message, if the attempt failed. The
  1379. // attempts are in order the recorder(s) was attempted. If successful a
  1380. // successful connection is made, the last attempt in the slice is the
  1381. // attempt for connected recorder.
  1382. func (ss *sshSession) connectToRecorder(ctx context.Context, recs []netip.AddrPort) (io.WriteCloser, []*tailcfg.SSHRecordingAttempt, <-chan error, error) {
  1383. if len(recs) == 0 {
  1384. return nil, nil, nil, errors.New("no recorders configured")
  1385. }
  1386. // We use a special context for dialing the recorder, so that we can
  1387. // limit the time we spend dialing to 30 seconds and still have an
  1388. // unbounded context for the upload.
  1389. dialCtx, dialCancel := context.WithTimeout(ctx, 30*time.Second)
  1390. defer dialCancel()
  1391. hc, err := ss.sessionRecordingClient(dialCtx)
  1392. if err != nil {
  1393. return nil, nil, nil, err
  1394. }
  1395. var errs []error
  1396. var attempts []*tailcfg.SSHRecordingAttempt
  1397. for _, ap := range recs {
  1398. attempt := &tailcfg.SSHRecordingAttempt{
  1399. Recorder: ap,
  1400. }
  1401. attempts = append(attempts, attempt)
  1402. // We dial the recorder and wait for it to send a 100-continue
  1403. // response before returning from this function. This ensures that
  1404. // the recorder is ready to accept the recording.
  1405. // got100 is closed when we receive the 100-continue response.
  1406. got100 := make(chan struct{})
  1407. ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
  1408. Got100Continue: func() {
  1409. close(got100)
  1410. },
  1411. })
  1412. pr, pw := io.Pipe()
  1413. req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://%s:%d/record", ap.Addr(), ap.Port()), pr)
  1414. if err != nil {
  1415. err = fmt.Errorf("recording: error starting recording: %w", err)
  1416. attempt.FailureMessage = err.Error()
  1417. errs = append(errs, err)
  1418. continue
  1419. }
  1420. // We set the Expect header to 100-continue, so that the recorder
  1421. // will send a 100-continue response before it starts reading the
  1422. // request body.
  1423. req.Header.Set("Expect", "100-continue")
  1424. // errChan is used to indicate the result of the request.
  1425. errChan := make(chan error, 1)
  1426. go func() {
  1427. resp, err := hc.Do(req)
  1428. if err != nil {
  1429. errChan <- fmt.Errorf("recording: error starting recording: %w", err)
  1430. return
  1431. }
  1432. if resp.StatusCode != 200 {
  1433. errChan <- fmt.Errorf("recording: unexpected status: %v", resp.Status)
  1434. return
  1435. }
  1436. errChan <- nil
  1437. }()
  1438. select {
  1439. case <-got100:
  1440. case err := <-errChan:
  1441. // If we get an error before we get the 100-continue response,
  1442. // we need to try another recorder.
  1443. if err == nil {
  1444. // If the error is nil, we got a 200 response, which
  1445. // is unexpected as we haven't sent any data yet.
  1446. err = errors.New("recording: unexpected EOF")
  1447. }
  1448. attempt.FailureMessage = err.Error()
  1449. errs = append(errs, err)
  1450. continue
  1451. }
  1452. return pw, attempts, errChan, nil
  1453. }
  1454. return nil, attempts, nil, multierr.New(errs...)
  1455. }
  1456. func (ss *sshSession) openFileForRecording(now time.Time) (_ io.WriteCloser, err error) {
  1457. varRoot := ss.conn.srv.lb.TailscaleVarRoot()
  1458. if varRoot == "" {
  1459. return nil, errors.New("no var root for recording storage")
  1460. }
  1461. dir := filepath.Join(varRoot, "ssh-sessions")
  1462. if err := os.MkdirAll(dir, 0700); err != nil {
  1463. return nil, err
  1464. }
  1465. f, err := os.CreateTemp(dir, fmt.Sprintf("ssh-session-%v-*.cast", now.UnixNano()))
  1466. if err != nil {
  1467. return nil, err
  1468. }
  1469. return f, nil
  1470. }
  1471. // startNewRecording starts a new SSH session recording.
  1472. // It may return a nil recording if recording is not available.
  1473. func (ss *sshSession) startNewRecording() (_ *recording, err error) {
  1474. // We store the node key as soon as possible when creating
  1475. // a new recording incase of FUS.
  1476. nodeKey := ss.conn.srv.lb.NodeKey()
  1477. if nodeKey.IsZero() {
  1478. return nil, errors.New("ssh server is unavailable: no node key")
  1479. }
  1480. recorders, onFailure := ss.recorders()
  1481. var localRecording bool
  1482. if len(recorders) == 0 {
  1483. if recordSSHToLocalDisk() {
  1484. localRecording = true
  1485. } else {
  1486. return nil, errors.New("no recorders configured")
  1487. }
  1488. }
  1489. var w ssh.Window
  1490. if ptyReq, _, isPtyReq := ss.Pty(); isPtyReq {
  1491. w = ptyReq.Window
  1492. }
  1493. term := envValFromList(ss.Environ(), "TERM")
  1494. if term == "" {
  1495. term = "xterm-256color" // something non-empty
  1496. }
  1497. now := time.Now()
  1498. rec := &recording{
  1499. ss: ss,
  1500. start: now,
  1501. failOpen: onFailure == nil || onFailure.TerminateSessionWithMessage == "",
  1502. }
  1503. // We want to use a background context for uploading and not ss.ctx.
  1504. // ss.ctx is closed when the session closes, but we don't want to break the upload at that time.
  1505. // Instead we want to wait for the session to close the writer when it finishes.
  1506. ctx := context.Background()
  1507. if localRecording {
  1508. rec.out, err = ss.openFileForRecording(now)
  1509. if err != nil {
  1510. return nil, err
  1511. }
  1512. } else {
  1513. var errChan <-chan error
  1514. var attempts []*tailcfg.SSHRecordingAttempt
  1515. rec.out, attempts, errChan, err = ss.connectToRecorder(ctx, recorders)
  1516. if err != nil {
  1517. if onFailure != nil && onFailure.NotifyURL != "" && len(attempts) > 0 {
  1518. eventType := tailcfg.SSHSessionRecordingFailed
  1519. if onFailure.RejectSessionWithMessage != "" {
  1520. eventType = tailcfg.SSHSessionRecordingRejected
  1521. }
  1522. ss.notifyControl(ctx, nodeKey, eventType, attempts, onFailure.NotifyURL)
  1523. }
  1524. if onFailure != nil && onFailure.RejectSessionWithMessage != "" {
  1525. ss.logf("recording: error starting recording (rejecting session): %v", err)
  1526. return nil, userVisibleError{
  1527. error: err,
  1528. msg: onFailure.RejectSessionWithMessage,
  1529. }
  1530. }
  1531. ss.logf("recording: error starting recording (failing open): %v", err)
  1532. return nil, nil
  1533. }
  1534. go func() {
  1535. err := <-errChan
  1536. if err == nil {
  1537. // Success.
  1538. ss.logf("recording: finished uploading recording")
  1539. return
  1540. }
  1541. if onFailure != nil && onFailure.NotifyURL != "" && len(attempts) > 0 {
  1542. lastAttempt := attempts[len(attempts)-1]
  1543. lastAttempt.FailureMessage = err.Error()
  1544. eventType := tailcfg.SSHSessionRecordingFailed
  1545. if onFailure.TerminateSessionWithMessage != "" {
  1546. eventType = tailcfg.SSHSessionRecordingTerminated
  1547. }
  1548. ss.notifyControl(ctx, nodeKey, eventType, attempts, onFailure.NotifyURL)
  1549. }
  1550. if onFailure != nil && onFailure.TerminateSessionWithMessage != "" {
  1551. ss.logf("recording: error uploading recording (closing session): %v", err)
  1552. ss.cancelCtx(userVisibleError{
  1553. error: err,
  1554. msg: onFailure.TerminateSessionWithMessage,
  1555. })
  1556. return
  1557. }
  1558. ss.logf("recording: error uploading recording (failing open): %v", err)
  1559. }()
  1560. }
  1561. ch := CastHeader{
  1562. Version: 2,
  1563. Width: w.Width,
  1564. Height: w.Height,
  1565. Timestamp: now.Unix(),
  1566. Command: strings.Join(ss.Command(), " "),
  1567. Env: map[string]string{
  1568. "TERM": term,
  1569. // TODO(bradfitz): anything else important?
  1570. // including all seems noisey, but maybe we should
  1571. // for auditing. But first need to break
  1572. // launchProcess's startWithStdPipes and
  1573. // startWithPTY up so that they first return the cmd
  1574. // without starting it, and then a step that starts
  1575. // it. Then we can (1) make the cmd, (2) start the
  1576. // recording, (3) start the process.
  1577. },
  1578. SSHUser: ss.conn.info.sshUser,
  1579. LocalUser: ss.conn.localUser.Username,
  1580. SrcNode: strings.TrimSuffix(ss.conn.info.node.Name(), "."),
  1581. SrcNodeID: ss.conn.info.node.StableID(),
  1582. ConnectionID: ss.conn.connID,
  1583. }
  1584. if !ss.conn.info.node.IsTagged() {
  1585. ch.SrcNodeUser = ss.conn.info.uprof.LoginName
  1586. ch.SrcNodeUserID = ss.conn.info.node.User()
  1587. } else {
  1588. ch.SrcNodeTags = ss.conn.info.node.Tags().AsSlice()
  1589. }
  1590. j, err := json.Marshal(ch)
  1591. if err != nil {
  1592. return nil, err
  1593. }
  1594. j = append(j, '\n')
  1595. if _, err := rec.out.Write(j); err != nil {
  1596. if errors.Is(err, io.ErrClosedPipe) && ss.ctx.Err() != nil {
  1597. // If we got an io.ErrClosedPipe, it's likely because
  1598. // the recording server closed the connection on us. Return
  1599. // the original context error instead.
  1600. return nil, context.Cause(ss.ctx)
  1601. }
  1602. return nil, err
  1603. }
  1604. return rec, nil
  1605. }
  1606. // notifyControl sends a SSHEventNotifyRequest to control over noise.
  1607. // A SSHEventNotifyRequest is sent when an action or state reached during
  1608. // an SSH session is a defined EventType.
  1609. func (ss *sshSession) notifyControl(ctx context.Context, nodeKey key.NodePublic, notifyType tailcfg.SSHEventType, attempts []*tailcfg.SSHRecordingAttempt, url string) {
  1610. re := tailcfg.SSHEventNotifyRequest{
  1611. EventType: notifyType,
  1612. ConnectionID: ss.conn.connID,
  1613. CapVersion: tailcfg.CurrentCapabilityVersion,
  1614. NodeKey: nodeKey,
  1615. SrcNode: ss.conn.info.node.ID(),
  1616. SSHUser: ss.conn.info.sshUser,
  1617. LocalUser: ss.conn.localUser.Username,
  1618. RecordingAttempts: attempts,
  1619. }
  1620. body, err := json.Marshal(re)
  1621. if err != nil {
  1622. ss.logf("notifyControl: unable to marshal SSHNotifyRequest:", err)
  1623. return
  1624. }
  1625. req, err := http.NewRequestWithContext(ctx, httpm.POST, url, bytes.NewReader(body))
  1626. if err != nil {
  1627. ss.logf("notifyControl: unable to create request:", err)
  1628. return
  1629. }
  1630. resp, err := ss.conn.srv.lb.DoNoiseRequest(req)
  1631. if err != nil {
  1632. ss.logf("notifyControl: unable to send noise request:", err)
  1633. return
  1634. }
  1635. if resp.StatusCode != http.StatusCreated {
  1636. ss.logf("notifyControl: noise request returned status code %v", resp.StatusCode)
  1637. return
  1638. }
  1639. }
  1640. // recording is the state for an SSH session recording.
  1641. type recording struct {
  1642. ss *sshSession
  1643. start time.Time
  1644. // failOpen specifies whether the session should be allowed to
  1645. // continue if writing to the recording fails.
  1646. failOpen bool
  1647. mu sync.Mutex // guards writes to, close of out
  1648. out io.WriteCloser
  1649. }
  1650. func (r *recording) Close() error {
  1651. r.mu.Lock()
  1652. defer r.mu.Unlock()
  1653. if r.out == nil {
  1654. return nil
  1655. }
  1656. err := r.out.Close()
  1657. r.out = nil
  1658. return err
  1659. }
  1660. // writer returns an io.Writer around w that first records the write.
  1661. //
  1662. // The dir should be "i" for input or "o" for output.
  1663. //
  1664. // If r is nil, it returns w unchanged.
  1665. //
  1666. // Currently (2023-03-21) we only record output, not input.
  1667. func (r *recording) writer(dir string, w io.Writer) io.Writer {
  1668. if r == nil {
  1669. return w
  1670. }
  1671. if dir == "i" {
  1672. // TODO: record input? Maybe not, since it might contain
  1673. // passwords.
  1674. return w
  1675. }
  1676. return &loggingWriter{r: r, dir: dir, w: w}
  1677. }
  1678. // loggingWriter is an io.Writer wrapper that writes first an
  1679. // asciinema JSON cast format recording line, and then writes to w.
  1680. type loggingWriter struct {
  1681. r *recording
  1682. dir string // "i" or "o" (input or output)
  1683. w io.Writer // underlying Writer, after writing to r.out
  1684. // recordingFailedOpen specifies whether we've failed to write to
  1685. // r.out and should stop trying. It is set to true if we fail to write
  1686. // to r.out and r.failOpen is set.
  1687. recordingFailedOpen bool
  1688. }
  1689. func (w *loggingWriter) Write(p []byte) (n int, err error) {
  1690. if !w.recordingFailedOpen {
  1691. j, err := json.Marshal([]any{
  1692. time.Since(w.r.start).Seconds(),
  1693. w.dir,
  1694. string(p),
  1695. })
  1696. if err != nil {
  1697. return 0, err
  1698. }
  1699. j = append(j, '\n')
  1700. if err := w.writeCastLine(j); err != nil {
  1701. if !w.r.failOpen {
  1702. return 0, err
  1703. }
  1704. w.recordingFailedOpen = true
  1705. }
  1706. }
  1707. return w.w.Write(p)
  1708. }
  1709. func (w loggingWriter) writeCastLine(j []byte) error {
  1710. w.r.mu.Lock()
  1711. defer w.r.mu.Unlock()
  1712. if w.r.out == nil {
  1713. return errors.New("logger closed")
  1714. }
  1715. _, err := w.r.out.Write(j)
  1716. if err != nil {
  1717. return fmt.Errorf("logger Write: %w", err)
  1718. }
  1719. return nil
  1720. }
  1721. func envValFromList(env []string, wantKey string) (v string) {
  1722. for _, kv := range env {
  1723. if thisKey, v, ok := strings.Cut(kv, "="); ok && envEq(thisKey, wantKey) {
  1724. return v
  1725. }
  1726. }
  1727. return ""
  1728. }
  1729. // envEq reports whether environment variable a == b for the current
  1730. // operating system.
  1731. func envEq(a, b string) bool {
  1732. if runtime.GOOS == "windows" {
  1733. return strings.EqualFold(a, b)
  1734. }
  1735. return a == b
  1736. }
  1737. var (
  1738. metricActiveSessions = clientmetric.NewGauge("ssh_active_sessions")
  1739. metricIncomingConnections = clientmetric.NewCounter("ssh_incoming_connections")
  1740. metricPublicKeyConnections = clientmetric.NewCounter("ssh_publickey_connections") // total
  1741. metricPublicKeyAccepts = clientmetric.NewCounter("ssh_publickey_accepts") // accepted subset of ssh_publickey_connections
  1742. metricTerminalAccept = clientmetric.NewCounter("ssh_terminalaction_accept")
  1743. metricTerminalReject = clientmetric.NewCounter("ssh_terminalaction_reject")
  1744. metricTerminalInterrupt = clientmetric.NewCounter("ssh_terminalaction_interrupt")
  1745. metricTerminalMalformed = clientmetric.NewCounter("ssh_terminalaction_malformed")
  1746. metricTerminalFetchError = clientmetric.NewCounter("ssh_terminalaction_fetch_error")
  1747. metricHolds = clientmetric.NewCounter("ssh_holds")
  1748. metricPolicyChangeKick = clientmetric.NewCounter("ssh_policy_change_kick")
  1749. metricSFTP = clientmetric.NewCounter("ssh_sftp_sessions")
  1750. metricLocalPortForward = clientmetric.NewCounter("ssh_local_port_forward_requests")
  1751. metricRemotePortForward = clientmetric.NewCounter("ssh_remote_port_forward_requests")
  1752. )
  1753. // userVisibleError is a wrapper around an error that implements
  1754. // SSHTerminationError, so msg is written to their session.
  1755. type userVisibleError struct {
  1756. msg string
  1757. error
  1758. }
  1759. func (ue userVisibleError) SSHTerminationMessage() string { return ue.msg }
  1760. // SSHTerminationError is implemented by errors that terminate an SSH
  1761. // session and should be written to user's sessions.
  1762. type SSHTerminationError interface {
  1763. error
  1764. SSHTerminationMessage() string
  1765. }
  1766. func closeAll(cs ...io.Closer) {
  1767. for _, c := range cs {
  1768. if c != nil {
  1769. c.Close()
  1770. }
  1771. }
  1772. }