tailssh.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. "io/ioutil"
  18. "net"
  19. "net/http"
  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. "inet.af/netaddr"
  32. "tailscale.com/envknob"
  33. "tailscale.com/ipn/ipnlocal"
  34. "tailscale.com/logtail/backoff"
  35. "tailscale.com/net/tsaddr"
  36. "tailscale.com/tailcfg"
  37. "tailscale.com/tempfork/gliderlabs/ssh"
  38. "tailscale.com/types/logger"
  39. )
  40. var sshVerboseLogging = envknob.Bool("TS_DEBUG_SSH_VLOG")
  41. // TODO(bradfitz): this is all very temporary as code is temporarily
  42. // being moved around; it will be restructured and documented in
  43. // following commits.
  44. // Handle handles an SSH connection from c.
  45. func Handle(logf logger.Logf, lb *ipnlocal.LocalBackend, c net.Conn) error {
  46. tsd, err := os.Executable()
  47. if err != nil {
  48. return err
  49. }
  50. // TODO(bradfitz): make just one server for the whole process. rearrange
  51. // netstack's hooks to be a constructor given a lb instead. Then the *server
  52. // will have a HandleTailscaleConn method.
  53. srv := &server{
  54. lb: lb,
  55. logf: logf,
  56. tailscaledPath: tsd,
  57. }
  58. ss, err := srv.newSSHServer()
  59. if err != nil {
  60. return err
  61. }
  62. ss.HandleConn(c)
  63. // Return nil to signal to netstack's interception that it doesn't need to
  64. // log. If ss.HandleConn had problems, it can log itself (ideally on an
  65. // sshSession.logf).
  66. return nil
  67. }
  68. func (srv *server) newSSHServer() (*ssh.Server, error) {
  69. ss := &ssh.Server{
  70. Handler: srv.handleSSH,
  71. RequestHandlers: map[string]ssh.RequestHandler{},
  72. SubsystemHandlers: map[string]ssh.SubsystemHandler{},
  73. // Note: the direct-tcpip channel handler and LocalPortForwardingCallback
  74. // only adds support for forwarding ports from the local machine.
  75. // TODO(maisem/bradfitz): add remote port forwarding support.
  76. ChannelHandlers: map[string]ssh.ChannelHandler{
  77. "direct-tcpip": ssh.DirectTCPIPHandler,
  78. },
  79. Version: "SSH-2.0-Tailscale",
  80. LocalPortForwardingCallback: srv.mayForwardLocalPortTo,
  81. NoClientAuthCallback: func(m gossh.ConnMetadata) (*gossh.Permissions, error) {
  82. if srv.requiresPubKey(m.User(), m.LocalAddr(), m.RemoteAddr()) {
  83. return nil, errors.New("public key required") // any non-nil error will do
  84. }
  85. return nil, nil
  86. },
  87. PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool {
  88. if srv.acceptPubKey(ctx.User(), ctx.LocalAddr(), ctx.RemoteAddr(), key) {
  89. srv.logf("accepting SSH public key %s", bytes.TrimSpace(gossh.MarshalAuthorizedKey(key)))
  90. return true
  91. }
  92. srv.logf("rejecting SSH public key %s", bytes.TrimSpace(gossh.MarshalAuthorizedKey(key)))
  93. return false
  94. },
  95. }
  96. for k, v := range ssh.DefaultRequestHandlers {
  97. ss.RequestHandlers[k] = v
  98. }
  99. for k, v := range ssh.DefaultChannelHandlers {
  100. ss.ChannelHandlers[k] = v
  101. }
  102. for k, v := range ssh.DefaultSubsystemHandlers {
  103. ss.SubsystemHandlers[k] = v
  104. }
  105. keys, err := srv.lb.GetSSH_HostKeys()
  106. if err != nil {
  107. return nil, err
  108. }
  109. for _, signer := range keys {
  110. ss.AddHostKey(signer)
  111. }
  112. return ss, nil
  113. }
  114. type server struct {
  115. lb *ipnlocal.LocalBackend
  116. logf logger.Logf
  117. tailscaledPath string
  118. // mu protects activeSessions.
  119. mu sync.Mutex
  120. activeSessionByH map[string]*sshSession // ssh.SessionID (DH H) => that session
  121. activeSessionBySharedID map[string]*sshSession // yyymmddThhmmss-XXXXX => session
  122. }
  123. var (
  124. debugPolicyFile = envknob.String("TS_DEBUG_SSH_POLICY_FILE")
  125. debugIgnoreTailnetSSHPolicy = envknob.Bool("TS_DEBUG_SSH_IGNORE_TAILNET_POLICY")
  126. )
  127. // mayForwardLocalPortTo reports whether the ctx should be allowed to port forward
  128. // to the specified host and port.
  129. // TODO(bradfitz/maisem): should we have more checks on host/port?
  130. func (srv *server) mayForwardLocalPortTo(ctx ssh.Context, destinationHost string, destinationPort uint32) bool {
  131. ss, ok := srv.getSessionForContext(ctx)
  132. if !ok {
  133. return false
  134. }
  135. return ss.action.AllowLocalPortForwarding
  136. }
  137. // requiresPubKey reports whether the SSH server, during the auth negotiation
  138. // phase, should requires that the client send an SSH public key. (or, more
  139. // specifically, that "none" auth isn't acceptable)
  140. func (srv *server) requiresPubKey(sshUser string, localAddr, remoteAddr net.Addr) bool {
  141. pol, ok := srv.sshPolicy()
  142. if !ok {
  143. return false
  144. }
  145. a, ci, _, err := srv.evaluatePolicy(sshUser, localAddr, remoteAddr, nil)
  146. if err == nil && (a.Accept || a.HoldAndDelegate != "") {
  147. // Policy doesn't require a public key.
  148. return false
  149. }
  150. if ci == nil {
  151. // If we didn't get far enough along through evaluatePolicy to know the Tailscale
  152. // identify of the remote side then it's going to fail quickly later anyway.
  153. // Return false to accept "none" auth and reject the conn.
  154. return false
  155. }
  156. // Is there any rule that looks like it'd require a public key for this
  157. // sshUser?
  158. for _, r := range pol.Rules {
  159. if ci.ruleExpired(r) {
  160. continue
  161. }
  162. if mapLocalUser(r.SSHUsers, sshUser) == "" {
  163. continue
  164. }
  165. for _, p := range r.Principals {
  166. if principalMatchesTailscaleIdentity(p, ci) && len(p.PubKeys) > 0 {
  167. return true
  168. }
  169. }
  170. }
  171. return false
  172. }
  173. func (srv *server) acceptPubKey(sshUser string, localAddr, remoteAddr net.Addr, pubKey ssh.PublicKey) bool {
  174. a, _, _, err := srv.evaluatePolicy(sshUser, localAddr, remoteAddr, pubKey)
  175. if err != nil {
  176. return false
  177. }
  178. return a.Accept || a.HoldAndDelegate != ""
  179. }
  180. // sshPolicy returns the SSHPolicy for current node.
  181. // If there is no SSHPolicy in the netmap, it returns a debugPolicy
  182. // if one is defined.
  183. func (srv *server) sshPolicy() (_ *tailcfg.SSHPolicy, ok bool) {
  184. lb := srv.lb
  185. nm := lb.NetMap()
  186. if nm == nil {
  187. return nil, false
  188. }
  189. if pol := nm.SSHPolicy; pol != nil && !debugIgnoreTailnetSSHPolicy {
  190. return pol, true
  191. }
  192. if debugPolicyFile != "" {
  193. f, err := os.ReadFile(debugPolicyFile)
  194. if err != nil {
  195. srv.logf("error reading debug SSH policy file: %v", err)
  196. return nil, false
  197. }
  198. p := new(tailcfg.SSHPolicy)
  199. if err := json.Unmarshal(f, p); err != nil {
  200. srv.logf("invalid JSON in %v: %v", debugPolicyFile, err)
  201. return nil, false
  202. }
  203. return p, true
  204. }
  205. return nil, false
  206. }
  207. func asTailscaleIPPort(a net.Addr) (netaddr.IPPort, error) {
  208. ta, ok := a.(*net.TCPAddr)
  209. if !ok {
  210. return netaddr.IPPort{}, fmt.Errorf("non-TCP addr %T %v", a, a)
  211. }
  212. tanetaddr, ok := netaddr.FromStdIP(ta.IP)
  213. if !ok {
  214. return netaddr.IPPort{}, fmt.Errorf("unparseable addr %v", ta.IP)
  215. }
  216. if !tsaddr.IsTailscaleIP(tanetaddr) {
  217. return netaddr.IPPort{}, fmt.Errorf("non-Tailscale addr %v", ta.IP)
  218. }
  219. return netaddr.IPPortFrom(tanetaddr, uint16(ta.Port)), nil
  220. }
  221. // evaluatePolicy returns the SSHAction, sshConnInfo and localUser after
  222. // evaluating the sshUser and remoteAddr against the SSHPolicy. The remoteAddr
  223. // and localAddr params must be Tailscale IPs.
  224. //
  225. // The return sshConnInfo will be non-nil, even on some errors, if the
  226. // evaluation made it far enough to resolve the remoteAddr to a Tailscale IP.
  227. func (srv *server) evaluatePolicy(sshUser string, localAddr, remoteAddr net.Addr, pubKey ssh.PublicKey) (_ *tailcfg.SSHAction, _ *sshConnInfo, localUser string, _ error) {
  228. pol, ok := srv.sshPolicy()
  229. if !ok {
  230. return nil, nil, "", fmt.Errorf("tsshd: rejecting connection; no SSH policy")
  231. }
  232. srcIPP, err := asTailscaleIPPort(remoteAddr)
  233. if err != nil {
  234. return nil, nil, "", fmt.Errorf("tsshd: rejecting: %w", err)
  235. }
  236. dstIPP, err := asTailscaleIPPort(localAddr)
  237. if err != nil {
  238. return nil, nil, "", err
  239. }
  240. node, uprof, ok := srv.lb.WhoIs(srcIPP)
  241. if !ok {
  242. return nil, nil, "", fmt.Errorf("unknown Tailscale identity from src %v", srcIPP)
  243. }
  244. ci := &sshConnInfo{
  245. now: time.Now(),
  246. fetchPublicKeysURL: srv.fetchPublicKeysURL,
  247. sshUser: sshUser,
  248. src: srcIPP,
  249. dst: dstIPP,
  250. node: node,
  251. uprof: &uprof,
  252. pubKey: pubKey,
  253. }
  254. a, localUser, ok := evalSSHPolicy(pol, ci)
  255. if !ok {
  256. return nil, ci, "", fmt.Errorf("ssh: access denied for %q from %v", uprof.LoginName, ci.src.IP())
  257. }
  258. return a, ci, localUser, nil
  259. }
  260. func (srv *server) fetchPublicKeysURL(url string) ([]string, error) {
  261. if !strings.HasPrefix(url, "https://") {
  262. return nil, errors.New("invalid URL scheme")
  263. }
  264. // TODO(bradfitz): add caching
  265. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  266. defer cancel()
  267. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  268. if err != nil {
  269. return nil, err
  270. }
  271. res, err := http.DefaultClient.Do(req)
  272. if err != nil {
  273. return nil, err
  274. }
  275. defer res.Body.Close()
  276. if res.StatusCode != http.StatusOK {
  277. return nil, errors.New(res.Status)
  278. }
  279. all, err := io.ReadAll(io.LimitReader(res.Body, 4<<10))
  280. return strings.Split(string(all), "\n"), err
  281. }
  282. // handleSSH is invoked when a new SSH connection attempt is made.
  283. func (srv *server) handleSSH(s ssh.Session) {
  284. logf := srv.logf
  285. sshUser := s.User()
  286. action, ci, localUser, err := srv.evaluatePolicy(sshUser, s.LocalAddr(), s.RemoteAddr(), s.PublicKey())
  287. if err != nil {
  288. logf(err.Error())
  289. s.Exit(1)
  290. return
  291. }
  292. var lu *user.User
  293. if localUser != "" {
  294. lu, err = user.Lookup(localUser)
  295. if err != nil {
  296. logf("ssh: user Lookup %q: %v", localUser, err)
  297. s.Exit(1)
  298. return
  299. }
  300. }
  301. ss := srv.newSSHSession(s, ci, lu)
  302. ss.logf("handling new SSH connection from %v (%v) to ssh-user %q", ci.uprof.LoginName, ci.src.IP(), sshUser)
  303. action, err = ss.resolveTerminalAction(action)
  304. if err != nil {
  305. ss.logf("resolveTerminalAction: %v", err)
  306. io.WriteString(s.Stderr(), "Access denied: failed to resolve SSHAction.\n")
  307. s.Exit(1)
  308. return
  309. }
  310. if action.Reject || !action.Accept {
  311. ss.logf("access denied for %v (%v)", ci.uprof.LoginName, ci.src.IP())
  312. s.Exit(1)
  313. return
  314. }
  315. ss.logf("access granted for %v (%v) to ssh-user %q", ci.uprof.LoginName, ci.src.IP(), sshUser)
  316. ss.action = action
  317. ss.run()
  318. }
  319. // resolveTerminalAction either returns action (if it's Accept or Reject) or else
  320. // loops, fetching new SSHActions from the control plane.
  321. //
  322. // Any action with a Message in the chain will be printed to ss.
  323. //
  324. // The returned SSHAction will be either Reject or Accept.
  325. func (ss *sshSession) resolveTerminalAction(action *tailcfg.SSHAction) (*tailcfg.SSHAction, error) {
  326. // Loop processing/fetching Actions until one reaches a
  327. // terminal state (Accept, Reject, or invalid Action), or
  328. // until fetchSSHAction times out due to the context being
  329. // done (client disconnect) or its 30 minute timeout passes.
  330. // (Which is a long time for somebody to see login
  331. // instructions and go to a URL to do something.)
  332. for {
  333. if action.Message != "" {
  334. io.WriteString(ss.Stderr(), strings.Replace(action.Message, "\n", "\r\n", -1))
  335. }
  336. if action.Accept || action.Reject {
  337. return action, nil
  338. }
  339. url := action.HoldAndDelegate
  340. if url == "" {
  341. return nil, errors.New("reached Action that lacked Accept, Reject, and HoldAndDelegate")
  342. }
  343. url = ss.expandDelegateURL(url)
  344. var err error
  345. action, err = ss.srv.fetchSSHAction(ss.Context(), url)
  346. if err != nil {
  347. return nil, fmt.Errorf("fetching SSHAction from %s: %w", url, err)
  348. }
  349. }
  350. }
  351. func (ss *sshSession) expandDelegateURL(actionURL string) string {
  352. nm := ss.srv.lb.NetMap()
  353. var dstNodeID string
  354. if nm != nil {
  355. dstNodeID = fmt.Sprint(int64(nm.SelfNode.ID))
  356. }
  357. return strings.NewReplacer(
  358. "$SRC_NODE_IP", url.QueryEscape(ss.connInfo.src.IP().String()),
  359. "$SRC_NODE_ID", fmt.Sprint(int64(ss.connInfo.node.ID)),
  360. "$DST_NODE_IP", url.QueryEscape(ss.connInfo.dst.IP().String()),
  361. "$DST_NODE_ID", dstNodeID,
  362. "$SSH_USER", url.QueryEscape(ss.connInfo.sshUser),
  363. "$LOCAL_USER", url.QueryEscape(ss.localUser.Username),
  364. ).Replace(actionURL)
  365. }
  366. // sshSession is an accepted Tailscale SSH session.
  367. type sshSession struct {
  368. ssh.Session
  369. idH string // the RFC4253 sec8 hash H; don't share outside process
  370. sharedID string // ID that's shared with control
  371. logf logger.Logf
  372. ctx *sshContext // implements context.Context
  373. srv *server
  374. connInfo *sshConnInfo
  375. action *tailcfg.SSHAction
  376. localUser *user.User
  377. agentListener net.Listener // non-nil if agent-forwarding requested+allowed
  378. // initialized by launchProcess:
  379. cmd *exec.Cmd
  380. stdin io.WriteCloser
  381. stdout io.Reader
  382. stderr io.Reader // nil for pty sessions
  383. ptyReq *ssh.Pty // non-nil for pty sessions
  384. // We use this sync.Once to ensure that we only terminate the process once,
  385. // either it exits itself or is terminated
  386. exitOnce sync.Once
  387. }
  388. func (ss *sshSession) vlogf(format string, args ...interface{}) {
  389. if sshVerboseLogging {
  390. ss.logf(format, args...)
  391. }
  392. }
  393. func (srv *server) newSSHSession(s ssh.Session, ci *sshConnInfo, lu *user.User) *sshSession {
  394. sharedID := fmt.Sprintf("%s-%02x", ci.now.UTC().Format("20060102T150405"), randBytes(5))
  395. return &sshSession{
  396. Session: s,
  397. idH: s.Context().(ssh.Context).SessionID(),
  398. sharedID: sharedID,
  399. ctx: newSSHContext(),
  400. srv: srv,
  401. localUser: lu,
  402. connInfo: ci,
  403. logf: logger.WithPrefix(srv.logf, "ssh-session("+sharedID+"): "),
  404. }
  405. }
  406. func (srv *server) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHAction, error) {
  407. ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
  408. defer cancel()
  409. bo := backoff.NewBackoff("fetch-ssh-action", srv.logf, 10*time.Second)
  410. for {
  411. if err := ctx.Err(); err != nil {
  412. return nil, err
  413. }
  414. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  415. if err != nil {
  416. return nil, err
  417. }
  418. res, err := srv.lb.DoNoiseRequest(req)
  419. if err != nil {
  420. bo.BackOff(ctx, err)
  421. continue
  422. }
  423. if res.StatusCode != 200 {
  424. body, _ := io.ReadAll(res.Body)
  425. res.Body.Close()
  426. if len(body) > 1<<10 {
  427. body = body[:1<<10]
  428. }
  429. srv.logf("fetch of %v: %s, %s", url, res.Status, body)
  430. bo.BackOff(ctx, fmt.Errorf("unexpected status: %v", res.Status))
  431. continue
  432. }
  433. a := new(tailcfg.SSHAction)
  434. err = json.NewDecoder(res.Body).Decode(a)
  435. res.Body.Close()
  436. if err != nil {
  437. srv.logf("invalid next SSHAction JSON from %v: %v", url, err)
  438. bo.BackOff(ctx, err)
  439. continue
  440. }
  441. return a, nil
  442. }
  443. }
  444. // killProcessOnContextDone waits for ss.ctx to be done and kills the process,
  445. // unless the process has already exited.
  446. func (ss *sshSession) killProcessOnContextDone() {
  447. <-ss.ctx.Done()
  448. // Either the process has already existed, in which case this does nothing.
  449. // Or, the process is still running in which case this will kill it.
  450. ss.exitOnce.Do(func() {
  451. err := ss.ctx.Err()
  452. if serr, ok := err.(SSHTerminationError); ok {
  453. msg := serr.SSHTerminationMessage()
  454. if msg != "" {
  455. io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n")
  456. }
  457. }
  458. ss.logf("terminating SSH session from %v: %v", ss.connInfo.src.IP(), err)
  459. ss.cmd.Process.Kill()
  460. })
  461. }
  462. // sessionAction returns the SSHAction associated with the session.
  463. func (srv *server) getSessionForContext(sctx ssh.Context) (ss *sshSession, ok bool) {
  464. srv.mu.Lock()
  465. defer srv.mu.Unlock()
  466. ss, ok = srv.activeSessionByH[sctx.SessionID()]
  467. return
  468. }
  469. // startSession registers ss as an active session.
  470. func (srv *server) startSession(ss *sshSession) {
  471. srv.mu.Lock()
  472. defer srv.mu.Unlock()
  473. if srv.activeSessionByH == nil {
  474. srv.activeSessionByH = make(map[string]*sshSession)
  475. }
  476. if srv.activeSessionBySharedID == nil {
  477. srv.activeSessionBySharedID = make(map[string]*sshSession)
  478. }
  479. if ss.idH == "" {
  480. panic("empty idH")
  481. }
  482. if _, dup := srv.activeSessionByH[ss.idH]; dup {
  483. panic("dup idH")
  484. }
  485. if ss.sharedID == "" {
  486. panic("empty sharedID")
  487. }
  488. if _, dup := srv.activeSessionBySharedID[ss.sharedID]; dup {
  489. panic("dup sharedID")
  490. }
  491. srv.activeSessionByH[ss.idH] = ss
  492. srv.activeSessionBySharedID[ss.sharedID] = ss
  493. }
  494. // endSession unregisters s from the list of active sessions.
  495. func (srv *server) endSession(ss *sshSession) {
  496. srv.mu.Lock()
  497. defer srv.mu.Unlock()
  498. delete(srv.activeSessionByH, ss.idH)
  499. delete(srv.activeSessionBySharedID, ss.sharedID)
  500. }
  501. var errSessionDone = errors.New("session is done")
  502. // handleSSHAgentForwarding starts a Unix socket listener and in the background
  503. // forwards agent connections between the listenr and the ssh.Session.
  504. // On success, it assigns ss.agentListener.
  505. func (ss *sshSession) handleSSHAgentForwarding(s ssh.Session, lu *user.User) error {
  506. if !ssh.AgentRequested(ss) || !ss.action.AllowAgentForwarding {
  507. return nil
  508. }
  509. ss.logf("ssh: agent forwarding requested")
  510. ln, err := ssh.NewAgentListener()
  511. if err != nil {
  512. return err
  513. }
  514. defer func() {
  515. if err != nil && ln != nil {
  516. ln.Close()
  517. }
  518. }()
  519. uid, err := strconv.ParseUint(lu.Uid, 10, 32)
  520. if err != nil {
  521. return err
  522. }
  523. gid, err := strconv.ParseUint(lu.Gid, 10, 32)
  524. if err != nil {
  525. return err
  526. }
  527. socket := ln.Addr().String()
  528. dir := filepath.Dir(socket)
  529. // Make sure the socket is accessible by the user.
  530. if err := os.Chown(socket, int(uid), int(gid)); err != nil {
  531. return err
  532. }
  533. if err := os.Chmod(dir, 0755); err != nil {
  534. return err
  535. }
  536. go ssh.ForwardAgentConnections(ln, s)
  537. ss.agentListener = ln
  538. return nil
  539. }
  540. // recordSSH is a temporary dev knob to test the SSH recording
  541. // functionality and support off-node streaming.
  542. //
  543. // TODO(bradfitz,maisem): move this to SSHPolicy.
  544. var recordSSH = envknob.Bool("TS_DEBUG_LOG_SSH")
  545. // run is the entrypoint for a newly accepted SSH session.
  546. //
  547. // It handles ss once it's been accepted and determined
  548. // that it should run.
  549. func (ss *sshSession) run() {
  550. srv := ss.srv
  551. srv.startSession(ss)
  552. defer srv.endSession(ss)
  553. defer ss.ctx.CloseWithError(errSessionDone)
  554. if ss.action.SesssionDuration != 0 {
  555. t := time.AfterFunc(ss.action.SesssionDuration, func() {
  556. ss.ctx.CloseWithError(userVisibleError{
  557. fmt.Sprintf("Session timeout of %v elapsed.", ss.action.SesssionDuration),
  558. context.DeadlineExceeded,
  559. })
  560. })
  561. defer t.Stop()
  562. }
  563. logf := srv.logf
  564. lu := ss.localUser
  565. localUser := lu.Username
  566. if euid := os.Geteuid(); euid != 0 {
  567. if lu.Uid != fmt.Sprint(euid) {
  568. ss.logf("can't switch to user %q from process euid %v", localUser, euid)
  569. fmt.Fprintf(ss, "can't switch user\n")
  570. ss.Exit(1)
  571. return
  572. }
  573. }
  574. // Take control of the PTY so that we can configure it below.
  575. // See https://github.com/tailscale/tailscale/issues/4146
  576. ss.DisablePTYEmulation()
  577. if err := ss.handleSSHAgentForwarding(ss, lu); err != nil {
  578. ss.logf("agent forwarding failed: %v", err)
  579. } else if ss.agentListener != nil {
  580. // TODO(maisem/bradfitz): add a way to close all session resources
  581. defer ss.agentListener.Close()
  582. }
  583. var rec *recording // or nil if disabled
  584. if ss.shouldRecord() {
  585. var err error
  586. rec, err = ss.startNewRecording()
  587. if err != nil {
  588. fmt.Fprintf(ss, "can't start new recording\n")
  589. ss.logf("startNewRecording: %v", err)
  590. ss.Exit(1)
  591. return
  592. }
  593. defer rec.Close()
  594. }
  595. err := ss.launchProcess(ss.ctx)
  596. if err != nil {
  597. logf("start failed: %v", err.Error())
  598. ss.Exit(1)
  599. return
  600. }
  601. go ss.killProcessOnContextDone()
  602. go func() {
  603. _, err := io.Copy(rec.writer("i", ss.stdin), ss)
  604. if err != nil {
  605. // TODO: don't log in the success case.
  606. logf("ssh: stdin copy: %v", err)
  607. }
  608. ss.stdin.Close()
  609. }()
  610. go func() {
  611. _, err := io.Copy(rec.writer("o", ss), ss.stdout)
  612. if err != nil {
  613. // TODO: don't log in the success case.
  614. logf("ssh: stdout copy: %v", err)
  615. }
  616. }()
  617. // stderr is nil for ptys.
  618. if ss.stderr != nil {
  619. go func() {
  620. _, err := io.Copy(ss.Stderr(), ss.stderr)
  621. if err != nil {
  622. // TODO: don't log in the success case.
  623. logf("ssh: stderr copy: %v", err)
  624. }
  625. }()
  626. }
  627. err = ss.cmd.Wait()
  628. // This will either make the SSH Termination goroutine be a no-op,
  629. // or itself will be a no-op because the process was killed by the
  630. // aforementioned goroutine.
  631. ss.exitOnce.Do(func() {})
  632. if err == nil {
  633. ss.logf("Wait: ok")
  634. ss.Exit(0)
  635. return
  636. }
  637. if ee, ok := err.(*exec.ExitError); ok {
  638. code := ee.ProcessState.ExitCode()
  639. ss.logf("Wait: code=%v", code)
  640. ss.Exit(code)
  641. return
  642. }
  643. ss.logf("Wait: %v", err)
  644. ss.Exit(1)
  645. return
  646. }
  647. func (ss *sshSession) shouldRecord() bool {
  648. // for now only record pty sessions
  649. // TODO(bradfitz,maisem): make configurable on SSHPolicy and
  650. // support recording non-pty stuff too.
  651. _, _, isPtyReq := ss.Pty()
  652. return recordSSH && isPtyReq
  653. }
  654. type sshConnInfo struct {
  655. // now is the time to consider the present moment for the
  656. // purposes of rule evaluation.
  657. now time.Time
  658. // fetchPublicKeysURL, if non-nil, is a func to fetch the public
  659. // keys of a URL. The strings are in the the typical public
  660. // key "type base64-string [comment]" format seen at e.g. https://github.com/USER.keys
  661. fetchPublicKeysURL func(url string) ([]string, error)
  662. // sshUser is the requested local SSH username ("root", "alice", etc).
  663. sshUser string
  664. // src is the Tailscale IP and port that the connection came from.
  665. src netaddr.IPPort
  666. // dst is the Tailscale IP and port that the connection came for.
  667. dst netaddr.IPPort
  668. // node is srcIP's node.
  669. node *tailcfg.Node
  670. // uprof is node's UserProfile.
  671. uprof *tailcfg.UserProfile
  672. // pubKey is the public key presented by the client, or nil
  673. // if they haven't yet sent one (as in the early "none" phase
  674. // of authentication negotiation).
  675. pubKey ssh.PublicKey
  676. }
  677. func (ci *sshConnInfo) ruleExpired(r *tailcfg.SSHRule) bool {
  678. if r.RuleExpires == nil {
  679. return false
  680. }
  681. return r.RuleExpires.Before(ci.now)
  682. }
  683. func evalSSHPolicy(pol *tailcfg.SSHPolicy, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, ok bool) {
  684. for _, r := range pol.Rules {
  685. if a, localUser, err := matchRule(r, ci); err == nil {
  686. return a, localUser, true
  687. }
  688. }
  689. return nil, "", false
  690. }
  691. // internal errors for testing; they don't escape to callers or logs.
  692. var (
  693. errNilRule = errors.New("nil rule")
  694. errNilAction = errors.New("nil action")
  695. errRuleExpired = errors.New("rule expired")
  696. errPrincipalMatch = errors.New("principal didn't match")
  697. errUserMatch = errors.New("user didn't match")
  698. )
  699. func matchRule(r *tailcfg.SSHRule, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, err error) {
  700. if r == nil {
  701. return nil, "", errNilRule
  702. }
  703. if r.Action == nil {
  704. return nil, "", errNilAction
  705. }
  706. if ci.ruleExpired(r) {
  707. return nil, "", errRuleExpired
  708. }
  709. if !r.Action.Reject || r.SSHUsers != nil {
  710. localUser = mapLocalUser(r.SSHUsers, ci.sshUser)
  711. if localUser == "" {
  712. return nil, "", errUserMatch
  713. }
  714. }
  715. if !anyPrincipalMatches(r.Principals, ci) {
  716. return nil, "", errPrincipalMatch
  717. }
  718. return r.Action, localUser, nil
  719. }
  720. func mapLocalUser(ruleSSHUsers map[string]string, reqSSHUser string) (localUser string) {
  721. v, ok := ruleSSHUsers[reqSSHUser]
  722. if !ok {
  723. v = ruleSSHUsers["*"]
  724. }
  725. if v == "=" {
  726. return reqSSHUser
  727. }
  728. return v
  729. }
  730. func anyPrincipalMatches(ps []*tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
  731. for _, p := range ps {
  732. if p == nil {
  733. continue
  734. }
  735. if principalMatches(p, ci) {
  736. return true
  737. }
  738. }
  739. return false
  740. }
  741. func principalMatches(p *tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
  742. return principalMatchesTailscaleIdentity(p, ci) &&
  743. principalMatchesPubKey(p, ci)
  744. }
  745. // principalMatchesTailscaleIdentity reports whether one of p's four fields
  746. // that match the Tailscale identity match (Node, NodeIP, UserLogin, Any).
  747. // This function does not consider PubKeys.
  748. func principalMatchesTailscaleIdentity(p *tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
  749. if p.Any {
  750. return true
  751. }
  752. if !p.Node.IsZero() && ci.node != nil && p.Node == ci.node.StableID {
  753. return true
  754. }
  755. if p.NodeIP != "" {
  756. if ip, _ := netaddr.ParseIP(p.NodeIP); ip == ci.src.IP() {
  757. return true
  758. }
  759. }
  760. if p.UserLogin != "" && ci.uprof != nil && ci.uprof.LoginName == p.UserLogin {
  761. return true
  762. }
  763. return false
  764. }
  765. func principalMatchesPubKey(p *tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
  766. if len(p.PubKeys) == 0 {
  767. return true
  768. }
  769. if ci.pubKey == nil {
  770. return false
  771. }
  772. pubKeys := p.PubKeys
  773. if len(pubKeys) == 1 && strings.HasPrefix(pubKeys[0], "https://") {
  774. if ci.fetchPublicKeysURL == nil {
  775. // TODO: log?
  776. return false
  777. }
  778. var err error
  779. pubKeys, err = ci.fetchPublicKeysURL(pubKeys[0])
  780. if err != nil {
  781. // TODO: log?
  782. return false
  783. }
  784. }
  785. for _, pubKey := range pubKeys {
  786. if pubKeyMatchesAuthorizedKey(ci.pubKey, pubKey) {
  787. return true
  788. }
  789. }
  790. return false
  791. }
  792. func pubKeyMatchesAuthorizedKey(pubKey ssh.PublicKey, wantKey string) bool {
  793. wantKeyType, rest, ok := strings.Cut(wantKey, " ")
  794. if !ok {
  795. return false
  796. }
  797. if pubKey.Type() != wantKeyType {
  798. return false
  799. }
  800. wantKeyB64, _, _ := strings.Cut(rest, " ")
  801. wantKeyData, _ := base64.StdEncoding.DecodeString(wantKeyB64)
  802. return len(wantKeyData) > 0 && bytes.Equal(pubKey.Marshal(), wantKeyData)
  803. }
  804. func randBytes(n int) []byte {
  805. b := make([]byte, n)
  806. if _, err := rand.Read(b); err != nil {
  807. panic(err)
  808. }
  809. return b
  810. }
  811. // startNewRecording starts a new SSH session recording.
  812. //
  813. // It writes an asciinema file to
  814. // $TAILSCALE_VAR_ROOT/ssh-sessions/ssh-session-<unixtime>-*.cast.
  815. func (ss *sshSession) startNewRecording() (*recording, error) {
  816. var w ssh.Window
  817. if ptyReq, _, isPtyReq := ss.Pty(); isPtyReq {
  818. w = ptyReq.Window
  819. }
  820. term := envValFromList(ss.Environ(), "TERM")
  821. if term == "" {
  822. term = "xterm-256color" // something non-empty
  823. }
  824. now := time.Now()
  825. rec := &recording{
  826. ss: ss,
  827. start: now,
  828. }
  829. varRoot := ss.srv.lb.TailscaleVarRoot()
  830. if varRoot == "" {
  831. return nil, errors.New("no var root for recording storage")
  832. }
  833. dir := filepath.Join(varRoot, "ssh-sessions")
  834. if err := os.MkdirAll(dir, 0700); err != nil {
  835. return nil, err
  836. }
  837. f, err := ioutil.TempFile(dir, fmt.Sprintf("ssh-session-%v-*.cast", now.UnixNano()))
  838. if err != nil {
  839. return nil, err
  840. }
  841. rec.out = f
  842. // {"version": 2, "width": 221, "height": 84, "timestamp": 1647146075, "env": {"SHELL": "/bin/bash", "TERM": "screen"}}
  843. type CastHeader struct {
  844. Version int `json:"version"`
  845. Width int `json:"width"`
  846. Height int `json:"height"`
  847. Timestamp int64 `json:"timestamp"`
  848. Env map[string]string `json:"env"`
  849. }
  850. j, err := json.Marshal(CastHeader{
  851. Version: 2,
  852. Width: w.Width,
  853. Height: w.Height,
  854. Timestamp: now.Unix(),
  855. Env: map[string]string{
  856. "TERM": term,
  857. // TODO(bradiftz): anything else important?
  858. // including all seems noisey, but maybe we should
  859. // for auditing. But first need to break
  860. // launchProcess's startWithStdPipes and
  861. // startWithPTY up so that they first return the cmd
  862. // without starting it, and then a step that starts
  863. // it. Then we can (1) make the cmd, (2) start the
  864. // recording, (3) start the process.
  865. },
  866. })
  867. if err != nil {
  868. f.Close()
  869. return nil, err
  870. }
  871. ss.logf("starting asciinema recording to %s", f.Name())
  872. j = append(j, '\n')
  873. if _, err := f.Write(j); err != nil {
  874. f.Close()
  875. return nil, err
  876. }
  877. return rec, nil
  878. }
  879. // recording is the state for an SSH session recording.
  880. type recording struct {
  881. ss *sshSession
  882. start time.Time
  883. mu sync.Mutex // guards writes to, close of out
  884. out *os.File // nil if closed
  885. }
  886. func (r *recording) Close() error {
  887. r.mu.Lock()
  888. defer r.mu.Unlock()
  889. if r.out == nil {
  890. return nil
  891. }
  892. err := r.out.Close()
  893. r.out = nil
  894. return err
  895. }
  896. // writer returns an io.Writer around w that first records the write.
  897. //
  898. // The dir should be "i" for input or "o" for output.
  899. //
  900. // If r is nil, it returns w unchanged.
  901. func (r *recording) writer(dir string, w io.Writer) io.Writer {
  902. if r == nil {
  903. return w
  904. }
  905. return &loggingWriter{r, dir, w}
  906. }
  907. // loggingWriter is an io.Writer wrapper that writes first an
  908. // asciinema JSON cast format recording line, and then writes to w.
  909. type loggingWriter struct {
  910. r *recording
  911. dir string // "i" or "o" (input or output)
  912. w io.Writer // underlying Writer, after writing to r.out
  913. }
  914. func (w loggingWriter) Write(p []byte) (n int, err error) {
  915. j, err := json.Marshal([]interface{}{
  916. time.Since(w.r.start).Seconds(),
  917. w.dir,
  918. string(p),
  919. })
  920. if err != nil {
  921. return 0, err
  922. }
  923. j = append(j, '\n')
  924. if err := w.writeCastLine(j); err != nil {
  925. return 0, nil
  926. }
  927. return w.w.Write(p)
  928. }
  929. func (w loggingWriter) writeCastLine(j []byte) error {
  930. w.r.mu.Lock()
  931. defer w.r.mu.Unlock()
  932. if w.r.out == nil {
  933. return errors.New("logger closed")
  934. }
  935. _, err := w.r.out.Write(j)
  936. if err != nil {
  937. return fmt.Errorf("logger Write: %w", err)
  938. }
  939. return nil
  940. }
  941. func envValFromList(env []string, wantKey string) (v string) {
  942. for _, kv := range env {
  943. if thisKey, v, ok := strings.Cut(kv, "="); ok && envEq(thisKey, wantKey) {
  944. return v
  945. }
  946. }
  947. return ""
  948. }
  949. // envEq reports whether environment variable a == b for the current
  950. // operating system.
  951. func envEq(a, b string) bool {
  952. if runtime.GOOS == "windows" {
  953. return strings.EqualFold(a, b)
  954. }
  955. return a == b
  956. }