idtools_unix.go 8.1 KB

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