idtools_unix.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //go:build !windows
  2. package idtools // import "github.com/docker/docker/pkg/idtools"
  3. import (
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strconv"
  11. "sync"
  12. "syscall"
  13. "github.com/opencontainers/runc/libcontainer/user"
  14. )
  15. var (
  16. entOnce sync.Once
  17. getentCmd string
  18. )
  19. func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error {
  20. path, err := filepath.Abs(path)
  21. if err != nil {
  22. return err
  23. }
  24. stat, err := os.Stat(path)
  25. if err == nil {
  26. if !stat.IsDir() {
  27. return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR}
  28. }
  29. if !chownExisting {
  30. return nil
  31. }
  32. // short-circuit -- we were called with an existing directory and chown was requested
  33. return setPermissions(path, mode, owner, stat)
  34. }
  35. // make an array containing the original path asked for, plus (for mkAll == true)
  36. // all path components leading up to the complete path that don't exist before we MkdirAll
  37. // so that we can chown all of them properly at the end. If chownExisting is false, we won't
  38. // chown the full directory path if it exists
  39. var paths []string
  40. if os.IsNotExist(err) {
  41. paths = []string{path}
  42. }
  43. if mkAll {
  44. // walk back to "/" looking for directories which do not exist
  45. // and add them to the paths array for chown after creation
  46. dirPath := path
  47. for {
  48. dirPath = filepath.Dir(dirPath)
  49. if dirPath == "/" {
  50. break
  51. }
  52. if _, err = os.Stat(dirPath); err != nil && os.IsNotExist(err) {
  53. paths = append(paths, dirPath)
  54. }
  55. }
  56. if err = os.MkdirAll(path, mode); err != nil {
  57. return err
  58. }
  59. } else if err = os.Mkdir(path, mode); err != nil {
  60. return err
  61. }
  62. // even if it existed, we will chown the requested path + any subpaths that
  63. // didn't exist when we called MkdirAll
  64. for _, pathComponent := range paths {
  65. if err = setPermissions(pathComponent, mode, owner, nil); err != nil {
  66. return err
  67. }
  68. }
  69. return nil
  70. }
  71. // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
  72. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  73. func LookupUser(name string) (user.User, error) {
  74. // first try a local system files lookup using existing capabilities
  75. usr, err := user.LookupUser(name)
  76. if err == nil {
  77. return usr, nil
  78. }
  79. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  80. usr, err = getentUser(name)
  81. if err != nil {
  82. return user.User{}, err
  83. }
  84. return usr, nil
  85. }
  86. // LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid,
  87. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  88. func LookupUID(uid int) (user.User, error) {
  89. // first try a local system files lookup using existing capabilities
  90. usr, err := user.LookupUid(uid)
  91. if err == nil {
  92. return usr, nil
  93. }
  94. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  95. return getentUser(strconv.Itoa(uid))
  96. }
  97. func getentUser(name string) (user.User, error) {
  98. reader, err := callGetent("passwd", name)
  99. if err != nil {
  100. return user.User{}, err
  101. }
  102. users, err := user.ParsePasswd(reader)
  103. if err != nil {
  104. return user.User{}, err
  105. }
  106. if len(users) == 0 {
  107. return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", name)
  108. }
  109. return users[0], nil
  110. }
  111. // LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name,
  112. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  113. func LookupGroup(name string) (user.Group, error) {
  114. // first try a local system files lookup using existing capabilities
  115. group, err := user.LookupGroup(name)
  116. if err == nil {
  117. return group, nil
  118. }
  119. // local files lookup failed; attempt to call `getent` to query configured group dbs
  120. return getentGroup(name)
  121. }
  122. // LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID,
  123. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  124. func LookupGID(gid int) (user.Group, error) {
  125. // first try a local system files lookup using existing capabilities
  126. group, err := user.LookupGid(gid)
  127. if err == nil {
  128. return group, nil
  129. }
  130. // local files lookup failed; attempt to call `getent` to query configured group dbs
  131. return getentGroup(strconv.Itoa(gid))
  132. }
  133. func getentGroup(name string) (user.Group, error) {
  134. reader, err := callGetent("group", name)
  135. if err != nil {
  136. return user.Group{}, err
  137. }
  138. groups, err := user.ParseGroup(reader)
  139. if err != nil {
  140. return user.Group{}, err
  141. }
  142. if len(groups) == 0 {
  143. return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", name)
  144. }
  145. return groups[0], nil
  146. }
  147. func callGetent(database, key string) (io.Reader, error) {
  148. entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") })
  149. // if no `getent` command on host, can't do anything else
  150. if getentCmd == "" {
  151. return nil, fmt.Errorf("unable to find getent command")
  152. }
  153. command := exec.Command(getentCmd, database, key)
  154. // we run getent within container filesystem, but without /dev so /dev/null is not available for exec to mock stdin
  155. command.Stdin = io.NopCloser(bytes.NewReader(nil))
  156. out, err := command.CombinedOutput()
  157. if err != nil {
  158. exitCode, errC := getExitCode(err)
  159. if errC != nil {
  160. return nil, err
  161. }
  162. switch exitCode {
  163. case 1:
  164. return nil, fmt.Errorf("getent reported invalid parameters/database unknown")
  165. case 2:
  166. return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, database)
  167. case 3:
  168. return nil, fmt.Errorf("getent database doesn't support enumeration")
  169. default:
  170. return nil, err
  171. }
  172. }
  173. return bytes.NewReader(out), nil
  174. }
  175. // getExitCode returns the ExitStatus of the specified error if its type is
  176. // exec.ExitError, returns 0 and an error otherwise.
  177. func getExitCode(err error) (int, error) {
  178. exitCode := 0
  179. if exiterr, ok := err.(*exec.ExitError); ok {
  180. if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
  181. return procExit.ExitStatus(), nil
  182. }
  183. }
  184. return exitCode, fmt.Errorf("failed to get exit code")
  185. }
  186. // setPermissions performs a chown/chmod only if the uid/gid don't match what's requested
  187. // Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the
  188. // dir is on an NFS share, so don't call chown unless we absolutely must.
  189. // Likewise for setting permissions.
  190. func setPermissions(p string, mode os.FileMode, owner Identity, stat os.FileInfo) error {
  191. if stat == nil {
  192. var err error
  193. stat, err = os.Stat(p)
  194. if err != nil {
  195. return err
  196. }
  197. }
  198. if stat.Mode().Perm() != mode.Perm() {
  199. if err := os.Chmod(p, mode.Perm()); err != nil {
  200. return err
  201. }
  202. }
  203. ssi := stat.Sys().(*syscall.Stat_t)
  204. if ssi.Uid == uint32(owner.UID) && ssi.Gid == uint32(owner.GID) {
  205. return nil
  206. }
  207. return os.Chown(p, owner.UID, owner.GID)
  208. }
  209. // LoadIdentityMapping takes a requested username and
  210. // using the data from /etc/sub{uid,gid} ranges, creates the
  211. // proper uid and gid remapping ranges for that user/group pair
  212. func LoadIdentityMapping(name string) (IdentityMapping, error) {
  213. usr, err := LookupUser(name)
  214. if err != nil {
  215. return IdentityMapping{}, fmt.Errorf("could not get user for username %s: %v", name, err)
  216. }
  217. subuidRanges, err := lookupSubUIDRanges(usr)
  218. if err != nil {
  219. return IdentityMapping{}, err
  220. }
  221. subgidRanges, err := lookupSubGIDRanges(usr)
  222. if err != nil {
  223. return IdentityMapping{}, err
  224. }
  225. return IdentityMapping{
  226. UIDMaps: subuidRanges,
  227. GIDMaps: subgidRanges,
  228. }, nil
  229. }
  230. func lookupSubUIDRanges(usr user.User) ([]IDMap, error) {
  231. rangeList, err := parseSubuid(strconv.Itoa(usr.Uid))
  232. if err != nil {
  233. return nil, err
  234. }
  235. if len(rangeList) == 0 {
  236. rangeList, err = parseSubuid(usr.Name)
  237. if err != nil {
  238. return nil, err
  239. }
  240. }
  241. if len(rangeList) == 0 {
  242. return nil, fmt.Errorf("no subuid ranges found for user %q", usr.Name)
  243. }
  244. return createIDMap(rangeList), nil
  245. }
  246. func lookupSubGIDRanges(usr user.User) ([]IDMap, error) {
  247. rangeList, err := parseSubgid(strconv.Itoa(usr.Uid))
  248. if err != nil {
  249. return nil, err
  250. }
  251. if len(rangeList) == 0 {
  252. rangeList, err = parseSubgid(usr.Name)
  253. if err != nil {
  254. return nil, err
  255. }
  256. }
  257. if len(rangeList) == 0 {
  258. return nil, fmt.Errorf("no subgid ranges found for user %q", usr.Name)
  259. }
  260. return createIDMap(rangeList), nil
  261. }