tailssh.go 56 KB

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