idtools_unix.go 8.1 KB

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