tailssh.go 42 KB

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