user.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux || (darwin && !ios) || freebsd || openbsd
  4. package tailssh
  5. import (
  6. "context"
  7. "errors"
  8. "io"
  9. "log"
  10. "os"
  11. "os/exec"
  12. "os/user"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "go4.org/mem"
  20. "tailscale.com/envknob"
  21. "tailscale.com/hostinfo"
  22. "tailscale.com/util/lineread"
  23. "tailscale.com/version/distro"
  24. )
  25. // userMeta is a wrapper around *user.User with extra fields.
  26. type userMeta struct {
  27. user.User
  28. // loginShellCached is the user's login shell, if known
  29. // at the time of userLookup.
  30. loginShellCached string
  31. }
  32. // GroupIds returns the list of group IDs that the user is a member of.
  33. func (u *userMeta) GroupIds() ([]string, error) {
  34. if runtime.GOOS == "linux" && distro.Get() == distro.Gokrazy {
  35. // Gokrazy is a single-user appliance with ~no userspace.
  36. // There aren't users to look up (no /etc/passwd, etc)
  37. // so rather than fail below, just hardcode root.
  38. // TODO(bradfitz): fix os/user upstream instead?
  39. return []string{"0"}, nil
  40. }
  41. return u.User.GroupIds()
  42. }
  43. // userLookup is like os/user.Lookup but it returns a *userMeta wrapper
  44. // around a *user.User with extra fields.
  45. func userLookup(username string) (*userMeta, error) {
  46. if runtime.GOOS != "linux" {
  47. return userLookupStd(username)
  48. }
  49. // No getent on Gokrazy. So hard-code the login shell.
  50. if distro.Get() == distro.Gokrazy {
  51. um, err := userLookupStd(username)
  52. if err != nil {
  53. um.User = user.User{
  54. Uid: "0",
  55. Gid: "0",
  56. Username: "root",
  57. Name: "Gokrazy",
  58. HomeDir: "/",
  59. }
  60. }
  61. um.loginShellCached = "/tmp/serial-busybox/ash"
  62. return um, err
  63. }
  64. // On Linux, default to using "getent" to look up users so that
  65. // even with static tailscaled binaries without cgo (as we distribute),
  66. // we can still look up PAM/NSS users which the standard library's
  67. // os/user without cgo won't get (because of no libc hooks).
  68. // But if "getent" fails, userLookupGetent falls back to the standard
  69. // library anyway.
  70. return userLookupGetent(username)
  71. }
  72. func validUsername(uid string) bool {
  73. maxUid := 32
  74. if runtime.GOOS == "linux" {
  75. maxUid = 256
  76. }
  77. if len(uid) > maxUid || len(uid) == 0 {
  78. return false
  79. }
  80. for _, r := range uid {
  81. if r < ' ' || r == 0x7f || r == utf8.RuneError { // TODO(bradfitz): more?
  82. return false
  83. }
  84. }
  85. return true
  86. }
  87. func userLookupGetent(username string) (*userMeta, error) {
  88. // Do some basic validation before passing this string to "getent", even though
  89. // getent should do its own validation.
  90. if !validUsername(username) {
  91. return nil, errors.New("invalid username")
  92. }
  93. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  94. defer cancel()
  95. out, err := exec.CommandContext(ctx, "getent", "passwd", username).Output()
  96. if err != nil {
  97. log.Printf("error calling getent for user %q: %v", username, err)
  98. return userLookupStd(username)
  99. }
  100. // output is "alice:x:1001:1001:Alice Smith,,,:/home/alice:/bin/bash"
  101. f := strings.SplitN(strings.TrimSpace(string(out)), ":", 10)
  102. for len(f) < 7 {
  103. f = append(f, "")
  104. }
  105. um := &userMeta{
  106. User: user.User{
  107. Username: f[0],
  108. Uid: f[2],
  109. Gid: f[3],
  110. Name: f[4],
  111. HomeDir: f[5],
  112. },
  113. loginShellCached: f[6],
  114. }
  115. return um, nil
  116. }
  117. func userLookupStd(username string) (*userMeta, error) {
  118. u, err := user.Lookup(username)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return &userMeta{User: *u}, nil
  123. }
  124. func (u *userMeta) LoginShell() string {
  125. if u.loginShellCached != "" {
  126. // This field should be populated on Linux, at least, because
  127. // func userLookup on Linux uses "getent" to look up the user
  128. // and that populates it.
  129. return u.loginShellCached
  130. }
  131. switch runtime.GOOS {
  132. case "darwin":
  133. // Note: /Users/username is key, and not the same as u.HomeDir.
  134. out, _ := exec.Command("dscl", ".", "-read", filepath.Join("/Users", u.Username), "UserShell").Output()
  135. // out is "UserShell: /bin/bash"
  136. s, ok := strings.CutPrefix(string(out), "UserShell: ")
  137. if ok {
  138. return strings.TrimSpace(s)
  139. }
  140. }
  141. if e := os.Getenv("SHELL"); e != "" {
  142. return e
  143. }
  144. return "/bin/sh"
  145. }
  146. // defaultPathTmpl specifies the default PATH template to use for new sessions.
  147. //
  148. // If empty, a default value is used based on the OS & distro to match OpenSSH's
  149. // usually-hardcoded behavior. (see
  150. // https://github.com/tailscale/tailscale/issues/5285 for background).
  151. //
  152. // The template may contain @{HOME} or @{PAM_USER} which expand to the user's
  153. // home directory and username, respectively. (PAM is not used, despite the
  154. // name)
  155. var defaultPathTmpl = envknob.RegisterString("TAILSCALE_SSH_DEFAULT_PATH")
  156. func defaultPathForUser(u *user.User) string {
  157. if s := defaultPathTmpl(); s != "" {
  158. return expandDefaultPathTmpl(s, u)
  159. }
  160. isRoot := u.Uid == "0"
  161. switch distro.Get() {
  162. case distro.Debian:
  163. hi := hostinfo.New()
  164. if hi.Distro == "ubuntu" {
  165. // distro.Get's Debian includes Ubuntu. But see if it's actually Ubuntu.
  166. // Ubuntu doesn't empirically seem to distinguish between root and non-root for the default.
  167. // And it includes /snap/bin.
  168. return "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
  169. }
  170. if isRoot {
  171. return "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  172. }
  173. return "/usr/local/bin:/usr/bin:/bin:/usr/bn/games"
  174. case distro.NixOS:
  175. return defaultPathForUserOnNixOS(u)
  176. }
  177. if isRoot {
  178. return "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  179. }
  180. return "/usr/local/bin:/usr/bin:/bin"
  181. }
  182. func defaultPathForUserOnNixOS(u *user.User) string {
  183. var path string
  184. lineread.File("/etc/pam/environment", func(lineb []byte) error {
  185. if v := pathFromPAMEnvLine(lineb, u); v != "" {
  186. path = v
  187. return io.EOF // stop iteration
  188. }
  189. return nil
  190. })
  191. return path
  192. }
  193. func pathFromPAMEnvLine(line []byte, u *user.User) (path string) {
  194. if !mem.HasPrefix(mem.B(line), mem.S("PATH")) {
  195. return ""
  196. }
  197. rest := strings.TrimSpace(strings.TrimPrefix(string(line), "PATH"))
  198. if quoted, ok := strings.CutPrefix(rest, "DEFAULT="); ok {
  199. if path, err := strconv.Unquote(quoted); err == nil {
  200. return expandDefaultPathTmpl(path, u)
  201. }
  202. }
  203. return ""
  204. }
  205. func expandDefaultPathTmpl(t string, u *user.User) string {
  206. p := strings.NewReplacer(
  207. "@{HOME}", u.HomeDir,
  208. "@{PAM_USER}", u.Username,
  209. ).Replace(t)
  210. if strings.Contains(p, "@{") {
  211. // If there are unknown expansions, conservatively fail closed.
  212. return ""
  213. }
  214. return p
  215. }