tailssh.go 50 KB

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