tailssh.go 40 KB

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