idtools_unix.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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.UID, owner.GID, 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 {
  61. if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
  62. return err
  63. }
  64. }
  65. // even if it existed, we will chown the requested path + any subpaths that
  66. // didn't exist when we called MkdirAll
  67. for _, pathComponent := range paths {
  68. if err := setPermissions(pathComponent, mode, owner.UID, owner.GID, nil); err != nil {
  69. return err
  70. }
  71. }
  72. return nil
  73. }
  74. // CanAccess takes a valid (existing) directory and a uid, gid pair and determines
  75. // if that uid, gid pair has access (execute bit) to the directory
  76. func CanAccess(path string, pair Identity) bool {
  77. statInfo, err := os.Stat(path)
  78. if err != nil {
  79. return false
  80. }
  81. perms := statInfo.Mode().Perm()
  82. if perms&0o001 == 0o001 {
  83. // world access
  84. return true
  85. }
  86. ssi := statInfo.Sys().(*syscall.Stat_t)
  87. if ssi.Uid == uint32(pair.UID) && (perms&0o100 == 0o100) {
  88. // owner access.
  89. return true
  90. }
  91. if ssi.Gid == uint32(pair.GID) && (perms&0o010 == 0o010) {
  92. // group access.
  93. return true
  94. }
  95. return false
  96. }
  97. // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
  98. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  99. func LookupUser(name string) (user.User, error) {
  100. // first try a local system files lookup using existing capabilities
  101. usr, err := user.LookupUser(name)
  102. if err == nil {
  103. return usr, nil
  104. }
  105. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  106. usr, err = getentUser(name)
  107. if err != nil {
  108. return user.User{}, err
  109. }
  110. return usr, nil
  111. }
  112. // LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid,
  113. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  114. func LookupUID(uid int) (user.User, error) {
  115. // first try a local system files lookup using existing capabilities
  116. usr, err := user.LookupUid(uid)
  117. if err == nil {
  118. return usr, nil
  119. }
  120. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  121. return getentUser(strconv.Itoa(uid))
  122. }
  123. func getentUser(name string) (user.User, error) {
  124. reader, err := callGetent("passwd", name)
  125. if err != nil {
  126. return user.User{}, err
  127. }
  128. users, err := user.ParsePasswd(reader)
  129. if err != nil {
  130. return user.User{}, err
  131. }
  132. if len(users) == 0 {
  133. return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", name)
  134. }
  135. return users[0], nil
  136. }
  137. // LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name,
  138. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  139. func LookupGroup(name string) (user.Group, error) {
  140. // first try a local system files lookup using existing capabilities
  141. group, err := user.LookupGroup(name)
  142. if err == nil {
  143. return group, nil
  144. }
  145. // local files lookup failed; attempt to call `getent` to query configured group dbs
  146. return getentGroup(name)
  147. }
  148. // LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID,
  149. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  150. func LookupGID(gid int) (user.Group, error) {
  151. // first try a local system files lookup using existing capabilities
  152. group, err := user.LookupGid(gid)
  153. if err == nil {
  154. return group, nil
  155. }
  156. // local files lookup failed; attempt to call `getent` to query configured group dbs
  157. return getentGroup(strconv.Itoa(gid))
  158. }
  159. func getentGroup(name string) (user.Group, error) {
  160. reader, err := callGetent("group", name)
  161. if err != nil {
  162. return user.Group{}, err
  163. }
  164. groups, err := user.ParseGroup(reader)
  165. if err != nil {
  166. return user.Group{}, err
  167. }
  168. if len(groups) == 0 {
  169. return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", name)
  170. }
  171. return groups[0], nil
  172. }
  173. func callGetent(database, key string) (io.Reader, error) {
  174. entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") })
  175. // if no `getent` command on host, can't do anything else
  176. if getentCmd == "" {
  177. return nil, fmt.Errorf("unable to find getent command")
  178. }
  179. out, err := execCmd(getentCmd, database, key)
  180. if err != nil {
  181. exitCode, errC := getExitCode(err)
  182. if errC != nil {
  183. return nil, err
  184. }
  185. switch exitCode {
  186. case 1:
  187. return nil, fmt.Errorf("getent reported invalid parameters/database unknown")
  188. case 2:
  189. return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, database)
  190. case 3:
  191. return nil, fmt.Errorf("getent database doesn't support enumeration")
  192. default:
  193. return nil, err
  194. }
  195. }
  196. return bytes.NewReader(out), nil
  197. }
  198. // getExitCode returns the ExitStatus of the specified error if its type is
  199. // exec.ExitError, returns 0 and an error otherwise.
  200. func getExitCode(err error) (int, error) {
  201. exitCode := 0
  202. if exiterr, ok := err.(*exec.ExitError); ok {
  203. if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
  204. return procExit.ExitStatus(), nil
  205. }
  206. }
  207. return exitCode, fmt.Errorf("failed to get exit code")
  208. }
  209. // setPermissions performs a chown/chmod only if the uid/gid don't match what's requested
  210. // 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
  211. // dir is on an NFS share, so don't call chown unless we absolutely must.
  212. // Likewise for setting permissions.
  213. func setPermissions(p string, mode os.FileMode, uid, gid int, stat os.FileInfo) error {
  214. if stat == nil {
  215. var err error
  216. stat, err = os.Stat(p)
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. if stat.Mode().Perm() != mode.Perm() {
  222. if err := os.Chmod(p, mode.Perm()); err != nil {
  223. return err
  224. }
  225. }
  226. ssi := stat.Sys().(*syscall.Stat_t)
  227. if ssi.Uid == uint32(uid) && ssi.Gid == uint32(gid) {
  228. return nil
  229. }
  230. return os.Chown(p, uid, gid)
  231. }
  232. // LoadIdentityMapping takes a requested username and
  233. // using the data from /etc/sub{uid,gid} ranges, creates the
  234. // proper uid and gid remapping ranges for that user/group pair
  235. func LoadIdentityMapping(name string) (IdentityMapping, error) {
  236. usr, err := LookupUser(name)
  237. if err != nil {
  238. return IdentityMapping{}, fmt.Errorf("could not get user for username %s: %v", name, err)
  239. }
  240. subuidRanges, err := lookupSubUIDRanges(usr)
  241. if err != nil {
  242. return IdentityMapping{}, err
  243. }
  244. subgidRanges, err := lookupSubGIDRanges(usr)
  245. if err != nil {
  246. return IdentityMapping{}, err
  247. }
  248. return IdentityMapping{
  249. UIDMaps: subuidRanges,
  250. GIDMaps: subgidRanges,
  251. }, nil
  252. }
  253. func lookupSubUIDRanges(usr user.User) ([]IDMap, error) {
  254. rangeList, err := parseSubuid(strconv.Itoa(usr.Uid))
  255. if err != nil {
  256. return nil, err
  257. }
  258. if len(rangeList) == 0 {
  259. rangeList, err = parseSubuid(usr.Name)
  260. if err != nil {
  261. return nil, err
  262. }
  263. }
  264. if len(rangeList) == 0 {
  265. return nil, fmt.Errorf("no subuid ranges found for user %q", usr.Name)
  266. }
  267. return createIDMap(rangeList), nil
  268. }
  269. func lookupSubGIDRanges(usr user.User) ([]IDMap, error) {
  270. rangeList, err := parseSubgid(strconv.Itoa(usr.Uid))
  271. if err != nil {
  272. return nil, err
  273. }
  274. if len(rangeList) == 0 {
  275. rangeList, err = parseSubgid(usr.Name)
  276. if err != nil {
  277. return nil, err
  278. }
  279. }
  280. if len(rangeList) == 0 {
  281. return nil, fmt.Errorf("no subgid ranges found for user %q", usr.Name)
  282. }
  283. return createIDMap(rangeList), nil
  284. }