tailssh.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. "context"
  10. "crypto/rand"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "net"
  17. "net/http"
  18. "os"
  19. "os/exec"
  20. "os/user"
  21. "path/filepath"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/tailscale/ssh"
  28. "inet.af/netaddr"
  29. "tailscale.com/envknob"
  30. "tailscale.com/ipn/ipnlocal"
  31. "tailscale.com/logtail/backoff"
  32. "tailscale.com/net/tsaddr"
  33. "tailscale.com/tailcfg"
  34. "tailscale.com/types/logger"
  35. )
  36. // TODO(bradfitz): this is all very temporary as code is temporarily
  37. // being moved around; it will be restructured and documented in
  38. // following commits.
  39. // Handle handles an SSH connection from c.
  40. func Handle(logf logger.Logf, lb *ipnlocal.LocalBackend, c net.Conn) error {
  41. tsd, err := os.Executable()
  42. if err != nil {
  43. return err
  44. }
  45. srv := &server{
  46. lb: lb,
  47. logf: logf,
  48. tailscaledPath: tsd,
  49. }
  50. ss, err := srv.newSSHServer()
  51. if err != nil {
  52. return err
  53. }
  54. ss.HandleConn(c)
  55. return nil
  56. }
  57. func (srv *server) newSSHServer() (*ssh.Server, error) {
  58. ss := &ssh.Server{
  59. Handler: srv.handleSSH,
  60. RequestHandlers: map[string]ssh.RequestHandler{},
  61. SubsystemHandlers: map[string]ssh.SubsystemHandler{},
  62. // Note: the direct-tcpip channel handler and LocalPortForwardingCallback
  63. // only adds support for forwarding ports from the local machine.
  64. // TODO(maisem/bradfitz): add remote port forwarding support.
  65. ChannelHandlers: map[string]ssh.ChannelHandler{
  66. "direct-tcpip": ssh.DirectTCPIPHandler,
  67. },
  68. Version: "SSH-2.0-Tailscale",
  69. LocalPortForwardingCallback: srv.mayForwardLocalPortTo,
  70. }
  71. for k, v := range ssh.DefaultRequestHandlers {
  72. ss.RequestHandlers[k] = v
  73. }
  74. for k, v := range ssh.DefaultChannelHandlers {
  75. ss.ChannelHandlers[k] = v
  76. }
  77. for k, v := range ssh.DefaultSubsystemHandlers {
  78. ss.SubsystemHandlers[k] = v
  79. }
  80. keys, err := srv.lb.GetSSH_HostKeys()
  81. if err != nil {
  82. return nil, err
  83. }
  84. for _, signer := range keys {
  85. ss.AddHostKey(signer)
  86. }
  87. return ss, nil
  88. }
  89. type server struct {
  90. lb *ipnlocal.LocalBackend
  91. logf logger.Logf
  92. tailscaledPath string
  93. // mu protects activeSessions.
  94. mu sync.Mutex
  95. activeSessionByH map[string]*sshSession // ssh.SessionID (DH H) => that session
  96. activeSessionBySharedID map[string]*sshSession // yyymmddThhmmss-XXXXX => session
  97. }
  98. var debugPolicyFile = envknob.String("TS_DEBUG_SSH_POLICY_FILE")
  99. // mayForwardLocalPortTo reports whether the ctx should be allowed to port forward
  100. // to the specified host and port.
  101. // TODO(bradfitz/maisem): should we have more checks on host/port?
  102. func (srv *server) mayForwardLocalPortTo(ctx ssh.Context, destinationHost string, destinationPort uint32) bool {
  103. ss, ok := srv.getSessionForContext(ctx)
  104. if !ok {
  105. return false
  106. }
  107. return ss.action.AllowLocalPortForwarding
  108. }
  109. // sshPolicy returns the SSHPolicy for current node.
  110. // If there is no SSHPolicy in the netmap, it returns a debugPolicy
  111. // if one is defined.
  112. func (srv *server) sshPolicy() (_ *tailcfg.SSHPolicy, ok bool) {
  113. lb := srv.lb
  114. nm := lb.NetMap()
  115. if nm == nil {
  116. return nil, false
  117. }
  118. if pol := nm.SSHPolicy; pol != nil {
  119. return pol, true
  120. }
  121. if debugPolicyFile != "" {
  122. f, err := os.ReadFile(debugPolicyFile)
  123. if err != nil {
  124. srv.logf("error reading debug SSH policy file: %v", err)
  125. return nil, false
  126. }
  127. p := new(tailcfg.SSHPolicy)
  128. if err := json.Unmarshal(f, p); err != nil {
  129. srv.logf("invalid JSON in %v: %v", debugPolicyFile, err)
  130. return nil, false
  131. }
  132. return p, true
  133. }
  134. return nil, false
  135. }
  136. func asTailscaleIPPort(a net.Addr) (netaddr.IPPort, error) {
  137. ta, ok := a.(*net.TCPAddr)
  138. if !ok {
  139. return netaddr.IPPort{}, fmt.Errorf("non-TCP addr %T %v", a, a)
  140. }
  141. tanetaddr, ok := netaddr.FromStdIP(ta.IP)
  142. if !ok {
  143. return netaddr.IPPort{}, fmt.Errorf("unparseable addr %v", ta.IP)
  144. }
  145. if !tsaddr.IsTailscaleIP(tanetaddr) {
  146. return netaddr.IPPort{}, fmt.Errorf("non-Tailscale addr %v", ta.IP)
  147. }
  148. return netaddr.IPPortFrom(tanetaddr, uint16(ta.Port)), nil
  149. }
  150. // evaluatePolicy returns the SSHAction, sshConnInfo and localUser
  151. // after evaluating the sshUser and remoteAddr against the SSHPolicy.
  152. // The remoteAddr and localAddr params must be Tailscale IPs.
  153. func (srv *server) evaluatePolicy(sshUser string, localAddr, remoteAddr net.Addr) (_ *tailcfg.SSHAction, _ *sshConnInfo, localUser string, _ error) {
  154. logf := srv.logf
  155. lb := srv.lb
  156. logf("Handling SSH from %v for user %v", remoteAddr, sshUser)
  157. pol, ok := srv.sshPolicy()
  158. if !ok {
  159. return nil, nil, "", fmt.Errorf("tsshd: rejecting connection; no SSH policy")
  160. }
  161. srcIPP, err := asTailscaleIPPort(remoteAddr)
  162. if err != nil {
  163. return nil, nil, "", fmt.Errorf("tsshd: rejecting: %w", err)
  164. }
  165. dstIPP, err := asTailscaleIPPort(localAddr)
  166. if err != nil {
  167. return nil, nil, "", err
  168. }
  169. node, uprof, ok := lb.WhoIs(srcIPP)
  170. if !ok {
  171. return nil, nil, "", fmt.Errorf("Hello, %v. I don't know who you are.\n", srcIPP)
  172. }
  173. ci := &sshConnInfo{
  174. now: time.Now(),
  175. sshUser: sshUser,
  176. src: srcIPP,
  177. dst: dstIPP,
  178. node: node,
  179. uprof: &uprof,
  180. }
  181. a, localUser, ok := evalSSHPolicy(pol, ci)
  182. if !ok {
  183. return nil, nil, "", fmt.Errorf("ssh: access denied for %q from %v", uprof.LoginName, ci.src.IP())
  184. }
  185. return a, ci, localUser, nil
  186. }
  187. // handleSSH is invoked when a new SSH connection attempt is made.
  188. func (srv *server) handleSSH(s ssh.Session) {
  189. logf := srv.logf
  190. sshUser := s.User()
  191. action, ci, localUser, err := srv.evaluatePolicy(sshUser, s.LocalAddr(), s.RemoteAddr())
  192. if err != nil {
  193. logf(err.Error())
  194. s.Exit(1)
  195. return
  196. }
  197. // Loop processing/fetching Actions until one reaches a
  198. // terminal state (Accept, Reject, or invalid Action), or
  199. // until fetchSSHAction times out due to the context being
  200. // done (client disconnect) or its 30 minute timeout passes.
  201. // (Which is a long time for somebody to see login
  202. // instructions and go to a URL to do something.)
  203. ProcessAction:
  204. for {
  205. if action.Message != "" {
  206. io.WriteString(s.Stderr(), strings.Replace(action.Message, "\n", "\r\n", -1))
  207. }
  208. if action.Reject {
  209. logf("ssh: access denied for %q from %v", ci.uprof.LoginName, ci.src.IP())
  210. s.Exit(1)
  211. return
  212. }
  213. if action.Accept {
  214. break ProcessAction
  215. }
  216. url := action.HoldAndDelegate
  217. if url == "" {
  218. logf("ssh: access denied; SSHAction has neither Reject, Accept, or next step URL")
  219. s.Exit(1)
  220. return
  221. }
  222. action, err = srv.fetchSSHAction(s.Context(), url)
  223. if err != nil {
  224. logf("ssh: fetching SSAction from %s: %v", url, err)
  225. s.Exit(1)
  226. return
  227. }
  228. }
  229. lu, err := user.Lookup(localUser)
  230. if err != nil {
  231. logf("ssh: user Lookup %q: %v", localUser, err)
  232. s.Exit(1)
  233. return
  234. }
  235. ss := srv.newSSHSession(s, ci, lu, action)
  236. ss.run()
  237. }
  238. // sshSession is an accepted Tailscale SSH session.
  239. type sshSession struct {
  240. ssh.Session
  241. idH string // the RFC4253 sec8 hash H; don't share outside process
  242. sharedID string // ID that's shared with control
  243. logf logger.Logf
  244. ctx *sshContext // implements context.Context
  245. srv *server
  246. connInfo *sshConnInfo
  247. action *tailcfg.SSHAction
  248. localUser *user.User
  249. agentListener net.Listener // non-nil if agent-forwarding requested+allowed
  250. // initialized by launchProcess:
  251. cmd *exec.Cmd
  252. stdin io.WriteCloser
  253. stdout io.Reader
  254. stderr io.Reader // nil for pty sessions
  255. ptyReq *ssh.Pty // non-nil for pty sessions
  256. // We use this sync.Once to ensure that we only terminate the process once,
  257. // either it exits itself or is terminated
  258. exitOnce sync.Once
  259. }
  260. func (srv *server) newSSHSession(s ssh.Session, ci *sshConnInfo, lu *user.User, action *tailcfg.SSHAction) *sshSession {
  261. sharedID := fmt.Sprintf("%s-%02x", ci.now.UTC().Format("20060102T150405"), randBytes(5))
  262. return &sshSession{
  263. Session: s,
  264. idH: s.Context().(ssh.Context).SessionID(),
  265. sharedID: sharedID,
  266. ctx: newSSHContext(),
  267. srv: srv,
  268. action: action,
  269. localUser: lu,
  270. connInfo: ci,
  271. logf: logger.WithPrefix(srv.logf, "ssh-session("+sharedID+"): "),
  272. }
  273. }
  274. func (srv *server) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHAction, error) {
  275. ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
  276. defer cancel()
  277. bo := backoff.NewBackoff("fetch-ssh-action", srv.logf, 10*time.Second)
  278. for {
  279. if err := ctx.Err(); err != nil {
  280. return nil, err
  281. }
  282. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  283. if err != nil {
  284. return nil, err
  285. }
  286. res, err := srv.lb.DoNoiseRequest(req)
  287. if err != nil {
  288. bo.BackOff(ctx, err)
  289. continue
  290. }
  291. if res.StatusCode != 200 {
  292. res.Body.Close()
  293. bo.BackOff(ctx, fmt.Errorf("unexpected status: %v", res.Status))
  294. continue
  295. }
  296. a := new(tailcfg.SSHAction)
  297. if err := json.NewDecoder(res.Body).Decode(a); err != nil {
  298. bo.BackOff(ctx, err)
  299. continue
  300. }
  301. return a, nil
  302. }
  303. }
  304. // killProcessOnContextDone waits for ss.ctx to be done and kills the process,
  305. // unless the process has already exited.
  306. func (ss *sshSession) killProcessOnContextDone() {
  307. <-ss.ctx.Done()
  308. // Either the process has already existed, in which case this does nothing.
  309. // Or, the process is still running in which case this will kill it.
  310. ss.exitOnce.Do(func() {
  311. err := ss.ctx.Err()
  312. if serr, ok := err.(SSHTerminationError); ok {
  313. msg := serr.SSHTerminationMessage()
  314. if msg != "" {
  315. io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n")
  316. }
  317. }
  318. ss.logf("terminating SSH session from %v: %v", ss.connInfo.src.IP(), err)
  319. ss.cmd.Process.Kill()
  320. })
  321. }
  322. // sessionAction returns the SSHAction associated with the session.
  323. func (srv *server) getSessionForContext(sctx ssh.Context) (ss *sshSession, ok bool) {
  324. srv.mu.Lock()
  325. defer srv.mu.Unlock()
  326. ss, ok = srv.activeSessionByH[sctx.SessionID()]
  327. return
  328. }
  329. // startSession registers ss as an active session.
  330. func (srv *server) startSession(ss *sshSession) {
  331. srv.mu.Lock()
  332. defer srv.mu.Unlock()
  333. if srv.activeSessionByH == nil {
  334. srv.activeSessionByH = make(map[string]*sshSession)
  335. }
  336. if srv.activeSessionBySharedID == nil {
  337. srv.activeSessionBySharedID = make(map[string]*sshSession)
  338. }
  339. if ss.idH == "" {
  340. panic("empty idH")
  341. }
  342. if _, dup := srv.activeSessionByH[ss.idH]; dup {
  343. panic("dup idH")
  344. }
  345. if ss.sharedID == "" {
  346. panic("empty sharedID")
  347. }
  348. if _, dup := srv.activeSessionBySharedID[ss.sharedID]; dup {
  349. panic("dup sharedID")
  350. }
  351. srv.activeSessionByH[ss.idH] = ss
  352. srv.activeSessionBySharedID[ss.sharedID] = ss
  353. }
  354. // endSession unregisters s from the list of active sessions.
  355. func (srv *server) endSession(ss *sshSession) {
  356. srv.mu.Lock()
  357. defer srv.mu.Unlock()
  358. delete(srv.activeSessionByH, ss.idH)
  359. delete(srv.activeSessionBySharedID, ss.sharedID)
  360. }
  361. var errSessionDone = errors.New("session is done")
  362. // handleSSHAgentForwarding starts a Unix socket listener and in the background
  363. // forwards agent connections between the listenr and the ssh.Session.
  364. // On success, it assigns ss.agentListener.
  365. func (ss *sshSession) handleSSHAgentForwarding(s ssh.Session, lu *user.User) error {
  366. if !ssh.AgentRequested(ss) || !ss.action.AllowAgentForwarding {
  367. return nil
  368. }
  369. ss.logf("ssh: agent forwarding requested")
  370. ln, err := ssh.NewAgentListener()
  371. if err != nil {
  372. return err
  373. }
  374. defer func() {
  375. if err != nil && ln != nil {
  376. ln.Close()
  377. }
  378. }()
  379. uid, err := strconv.ParseUint(lu.Uid, 10, 32)
  380. if err != nil {
  381. return err
  382. }
  383. gid, err := strconv.ParseUint(lu.Gid, 10, 32)
  384. if err != nil {
  385. return err
  386. }
  387. socket := ln.Addr().String()
  388. dir := filepath.Dir(socket)
  389. // Make sure the socket is accessible by the user.
  390. if err := os.Chown(socket, int(uid), int(gid)); err != nil {
  391. return err
  392. }
  393. if err := os.Chmod(dir, 0755); err != nil {
  394. return err
  395. }
  396. go ssh.ForwardAgentConnections(ln, s)
  397. ss.agentListener = ln
  398. return nil
  399. }
  400. // recordSSH is a temporary dev knob to test the SSH recording
  401. // functionality and support off-node streaming.
  402. //
  403. // TODO(bradfitz,maisem): move this to SSHPolicy.
  404. var recordSSH = envknob.Bool("TS_DEBUG_LOG_SSH")
  405. // run is the entrypoint for a newly accepted SSH session.
  406. //
  407. // It handles ss once it's been accepted and determined
  408. // that it should run.
  409. func (ss *sshSession) run() {
  410. srv := ss.srv
  411. srv.startSession(ss)
  412. defer srv.endSession(ss)
  413. defer ss.ctx.CloseWithError(errSessionDone)
  414. if ss.action.SesssionDuration != 0 {
  415. t := time.AfterFunc(ss.action.SesssionDuration, func() {
  416. ss.ctx.CloseWithError(userVisibleError{
  417. fmt.Sprintf("Session timeout of %v elapsed.", ss.action.SesssionDuration),
  418. context.DeadlineExceeded,
  419. })
  420. })
  421. defer t.Stop()
  422. }
  423. logf := srv.logf
  424. lu := ss.localUser
  425. localUser := lu.Username
  426. if euid := os.Geteuid(); euid != 0 {
  427. if lu.Uid != fmt.Sprint(euid) {
  428. logf("ssh: can't switch to user %q from process euid %v", localUser, euid)
  429. fmt.Fprintf(ss, "can't switch user\n")
  430. ss.Exit(1)
  431. return
  432. }
  433. }
  434. // Take control of the PTY so that we can configure it below.
  435. // See https://github.com/tailscale/tailscale/issues/4146
  436. ss.DisablePTYEmulation()
  437. if err := ss.handleSSHAgentForwarding(ss, lu); err != nil {
  438. logf("ssh: agent forwarding failed: %v", err)
  439. } else if ss.agentListener != nil {
  440. // TODO(maisem/bradfitz): add a way to close all session resources
  441. defer ss.agentListener.Close()
  442. }
  443. var rec *recording // or nil if disabled
  444. if ss.shouldRecord() {
  445. var err error
  446. rec, err = ss.startNewRecording()
  447. if err != nil {
  448. fmt.Fprintf(ss, "can't start new recording\n")
  449. logf("startNewRecording: %v", err)
  450. ss.Exit(1)
  451. return
  452. }
  453. defer rec.Close()
  454. }
  455. err := ss.launchProcess(ss.ctx)
  456. if err != nil {
  457. logf("start failed: %v", err.Error())
  458. ss.Exit(1)
  459. return
  460. }
  461. go ss.killProcessOnContextDone()
  462. go func() {
  463. _, err := io.Copy(rec.writer("i", ss.stdin), ss)
  464. if err != nil {
  465. // TODO: don't log in the success case.
  466. logf("ssh: stdin copy: %v", err)
  467. }
  468. ss.stdin.Close()
  469. }()
  470. go func() {
  471. _, err := io.Copy(rec.writer("o", ss), ss.stdout)
  472. if err != nil {
  473. // TODO: don't log in the success case.
  474. logf("ssh: stdout copy: %v", err)
  475. }
  476. }()
  477. // stderr is nil for ptys.
  478. if ss.stderr != nil {
  479. go func() {
  480. _, err := io.Copy(ss.Stderr(), ss.stderr)
  481. if err != nil {
  482. // TODO: don't log in the success case.
  483. logf("ssh: stderr copy: %v", err)
  484. }
  485. }()
  486. }
  487. err = ss.cmd.Wait()
  488. // This will either make the SSH Termination goroutine be a no-op,
  489. // or itself will be a no-op because the process was killed by the
  490. // aforementioned goroutine.
  491. ss.exitOnce.Do(func() {})
  492. if err == nil {
  493. logf("ssh: Wait: ok")
  494. ss.Exit(0)
  495. return
  496. }
  497. if ee, ok := err.(*exec.ExitError); ok {
  498. code := ee.ProcessState.ExitCode()
  499. logf("ssh: Wait: code=%v", code)
  500. ss.Exit(code)
  501. return
  502. }
  503. logf("ssh: Wait: %v", err)
  504. ss.Exit(1)
  505. return
  506. }
  507. func (ss *sshSession) shouldRecord() bool {
  508. // for now only record pty sessions
  509. // TODO(bradfitz,maisem): make configurable on SSHPolicy and
  510. // support recording non-pty stuff too.
  511. _, _, isPtyReq := ss.Pty()
  512. return recordSSH && isPtyReq
  513. }
  514. type sshConnInfo struct {
  515. // now is the time to consider the present moment for the
  516. // purposes of rule evaluation.
  517. now time.Time
  518. // sshUser is the requested local SSH username ("root", "alice", etc).
  519. sshUser string
  520. // src is the Tailscale IP and port that the connection came from.
  521. src netaddr.IPPort
  522. // dst is the Tailscale IP and port that the connection came for.
  523. dst netaddr.IPPort
  524. // node is srcIP's node.
  525. node *tailcfg.Node
  526. // uprof is node's UserProfile.
  527. uprof *tailcfg.UserProfile
  528. }
  529. func evalSSHPolicy(pol *tailcfg.SSHPolicy, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, ok bool) {
  530. for _, r := range pol.Rules {
  531. if a, localUser, err := matchRule(r, ci); err == nil {
  532. return a, localUser, true
  533. }
  534. }
  535. return nil, "", false
  536. }
  537. // internal errors for testing; they don't escape to callers or logs.
  538. var (
  539. errNilRule = errors.New("nil rule")
  540. errNilAction = errors.New("nil action")
  541. errRuleExpired = errors.New("rule expired")
  542. errPrincipalMatch = errors.New("principal didn't match")
  543. errUserMatch = errors.New("user didn't match")
  544. )
  545. func matchRule(r *tailcfg.SSHRule, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, err error) {
  546. if r == nil {
  547. return nil, "", errNilRule
  548. }
  549. if r.Action == nil {
  550. return nil, "", errNilAction
  551. }
  552. if r.RuleExpires != nil && ci.now.After(*r.RuleExpires) {
  553. return nil, "", errRuleExpired
  554. }
  555. if !matchesPrincipal(r.Principals, ci) {
  556. return nil, "", errPrincipalMatch
  557. }
  558. if !r.Action.Reject || r.SSHUsers != nil {
  559. localUser = mapLocalUser(r.SSHUsers, ci.sshUser)
  560. if localUser == "" {
  561. return nil, "", errUserMatch
  562. }
  563. }
  564. return r.Action, localUser, nil
  565. }
  566. func mapLocalUser(ruleSSHUsers map[string]string, reqSSHUser string) (localUser string) {
  567. v, ok := ruleSSHUsers[reqSSHUser]
  568. if !ok {
  569. v = ruleSSHUsers["*"]
  570. }
  571. if v == "=" {
  572. return reqSSHUser
  573. }
  574. return v
  575. }
  576. func matchesPrincipal(ps []*tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
  577. for _, p := range ps {
  578. if p == nil {
  579. continue
  580. }
  581. if p.Any {
  582. return true
  583. }
  584. if !p.Node.IsZero() && ci.node != nil && p.Node == ci.node.StableID {
  585. return true
  586. }
  587. if p.NodeIP != "" {
  588. if ip, _ := netaddr.ParseIP(p.NodeIP); ip == ci.src.IP() {
  589. return true
  590. }
  591. }
  592. if p.UserLogin != "" && ci.uprof != nil && ci.uprof.LoginName == p.UserLogin {
  593. return true
  594. }
  595. }
  596. return false
  597. }
  598. func randBytes(n int) []byte {
  599. b := make([]byte, n)
  600. if _, err := rand.Read(b); err != nil {
  601. panic(err)
  602. }
  603. return b
  604. }
  605. // startNewRecording starts a new SSH session recording.
  606. //
  607. // It writes an asciinema file to
  608. // $TAILSCALE_VAR_ROOT/ssh-sessions/ssh-session-<unixtime>-*.cast.
  609. func (ss *sshSession) startNewRecording() (*recording, error) {
  610. var w ssh.Window
  611. if ptyReq, _, isPtyReq := ss.Pty(); isPtyReq {
  612. w = ptyReq.Window
  613. }
  614. term := envValFromList(ss.Environ(), "TERM")
  615. if term == "" {
  616. term = "xterm-256color" // something non-empty
  617. }
  618. now := time.Now()
  619. rec := &recording{
  620. ss: ss,
  621. start: now,
  622. }
  623. varRoot := ss.srv.lb.TailscaleVarRoot()
  624. if varRoot == "" {
  625. return nil, errors.New("no var root for recording storage")
  626. }
  627. dir := filepath.Join(varRoot, "ssh-sessions")
  628. if err := os.MkdirAll(dir, 0700); err != nil {
  629. return nil, err
  630. }
  631. f, err := ioutil.TempFile(dir, fmt.Sprintf("ssh-session-%v-*.cast", now.UnixNano()))
  632. if err != nil {
  633. return nil, err
  634. }
  635. rec.out = f
  636. // {"version": 2, "width": 221, "height": 84, "timestamp": 1647146075, "env": {"SHELL": "/bin/bash", "TERM": "screen"}}
  637. type CastHeader struct {
  638. Version int `json:"version"`
  639. Width int `json:"width"`
  640. Height int `json:"height"`
  641. Timestamp int64 `json:"timestamp"`
  642. Env map[string]string `json:"env"`
  643. }
  644. j, err := json.Marshal(CastHeader{
  645. Version: 2,
  646. Width: w.Width,
  647. Height: w.Height,
  648. Timestamp: now.Unix(),
  649. Env: map[string]string{
  650. "TERM": term,
  651. // TODO(bradiftz): anything else important?
  652. // including all seems noisey, but maybe we should
  653. // for auditing. But first need to break
  654. // launchProcess's startWithStdPipes and
  655. // startWithPTY up so that they first return the cmd
  656. // without starting it, and then a step that starts
  657. // it. Then we can (1) make the cmd, (2) start the
  658. // recording, (3) start the process.
  659. },
  660. })
  661. if err != nil {
  662. f.Close()
  663. return nil, err
  664. }
  665. ss.logf("starting asciinema recording to %s", f.Name())
  666. j = append(j, '\n')
  667. if _, err := f.Write(j); err != nil {
  668. f.Close()
  669. return nil, err
  670. }
  671. return rec, nil
  672. }
  673. // recording is the state for an SSH session recording.
  674. type recording struct {
  675. ss *sshSession
  676. start time.Time
  677. mu sync.Mutex // guards writes to, close of out
  678. out *os.File // nil if closed
  679. }
  680. func (r *recording) Close() error {
  681. r.mu.Lock()
  682. defer r.mu.Unlock()
  683. if r.out == nil {
  684. return nil
  685. }
  686. err := r.out.Close()
  687. r.out = nil
  688. return err
  689. }
  690. // writer returns an io.Writer around w that first records the write.
  691. //
  692. // The dir should be "i" for input or "o" for output.
  693. //
  694. // If r is nil, it returns w unchanged.
  695. func (r *recording) writer(dir string, w io.Writer) io.Writer {
  696. if r == nil {
  697. return w
  698. }
  699. return &loggingWriter{r, dir, w}
  700. }
  701. // loggingWriter is an io.Writer wrapper that writes first an
  702. // asciinema JSON cast format recording line, and then writes to w.
  703. type loggingWriter struct {
  704. r *recording
  705. dir string // "i" or "o" (input or output)
  706. w io.Writer // underlying Writer, after writing to r.out
  707. }
  708. func (w loggingWriter) Write(p []byte) (n int, err error) {
  709. j, err := json.Marshal([]interface{}{
  710. time.Since(w.r.start).Seconds(),
  711. w.dir,
  712. string(p),
  713. })
  714. if err != nil {
  715. return 0, err
  716. }
  717. j = append(j, '\n')
  718. if err := w.writeCastLine(j); err != nil {
  719. return 0, nil
  720. }
  721. return w.w.Write(p)
  722. }
  723. func (w loggingWriter) writeCastLine(j []byte) error {
  724. w.r.mu.Lock()
  725. defer w.r.mu.Unlock()
  726. if w.r.out == nil {
  727. return errors.New("logger closed")
  728. }
  729. _, err := w.r.out.Write(j)
  730. if err != nil {
  731. return fmt.Errorf("logger Write: %w", err)
  732. }
  733. return nil
  734. }
  735. func envValFromList(env []string, wantKey string) (v string) {
  736. for _, kv := range env {
  737. if thisKey, v, ok := strings.Cut(kv, "="); ok && envEq(thisKey, wantKey) {
  738. return v
  739. }
  740. }
  741. return ""
  742. }
  743. // envEq reports whether environment variable a == b for the current
  744. // operating system.
  745. func envEq(a, b string) bool {
  746. if runtime.GOOS == "windows" {
  747. return strings.EqualFold(a, b)
  748. }
  749. return a == b
  750. }