tailssh.go 56 KB

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