tailssh.go 51 KB

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