idtools_unix.go 8.0 KB

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