idtools_unix.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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/docker/docker/pkg/system"
  15. "github.com/opencontainers/runc/libcontainer/user"
  16. )
  17. var (
  18. entOnce sync.Once
  19. getentCmd string
  20. )
  21. func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error {
  22. path, err := filepath.Abs(path)
  23. if err != nil {
  24. return err
  25. }
  26. stat, err := system.Stat(path)
  27. if err == nil {
  28. if !stat.IsDir() {
  29. return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR}
  30. }
  31. if !chownExisting {
  32. return nil
  33. }
  34. // short-circuit--we were called with an existing directory and chown was requested
  35. return setPermissions(path, mode, owner.UID, owner.GID, stat)
  36. }
  37. // make an array containing the original path asked for, plus (for mkAll == true)
  38. // all path components leading up to the complete path that don't exist before we MkdirAll
  39. // so that we can chown all of them properly at the end. If chownExisting is false, we won't
  40. // chown the full directory path if it exists
  41. var paths []string
  42. if os.IsNotExist(err) {
  43. paths = []string{path}
  44. }
  45. if mkAll {
  46. // walk back to "/" looking for directories which do not exist
  47. // and add them to the paths array for chown after creation
  48. dirPath := path
  49. for {
  50. dirPath = filepath.Dir(dirPath)
  51. if dirPath == "/" {
  52. break
  53. }
  54. if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
  55. paths = append(paths, dirPath)
  56. }
  57. }
  58. if err := os.MkdirAll(path, mode); err != nil {
  59. return err
  60. }
  61. } else {
  62. if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
  63. return err
  64. }
  65. }
  66. // even if it existed, we will chown the requested path + any subpaths that
  67. // didn't exist when we called MkdirAll
  68. for _, pathComponent := range paths {
  69. if err := setPermissions(pathComponent, mode, owner.UID, owner.GID, nil); err != nil {
  70. return err
  71. }
  72. }
  73. return nil
  74. }
  75. // CanAccess takes a valid (existing) directory and a uid, gid pair and determines
  76. // if that uid, gid pair has access (execute bit) to the directory
  77. func CanAccess(path string, pair Identity) bool {
  78. statInfo, err := system.Stat(path)
  79. if err != nil {
  80. return false
  81. }
  82. perms := os.FileMode(statInfo.Mode()).Perm()
  83. if perms&0o001 == 0o001 {
  84. // world access
  85. return true
  86. }
  87. if statInfo.UID() == uint32(pair.UID) && (perms&0o100 == 0o100) {
  88. // owner access.
  89. return true
  90. }
  91. if statInfo.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 *system.StatT) error {
  214. if stat == nil {
  215. var err error
  216. stat, err = system.Stat(p)
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. if os.FileMode(stat.Mode()).Perm() != mode.Perm() {
  222. if err := os.Chmod(p, mode.Perm()); err != nil {
  223. return err
  224. }
  225. }
  226. if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) {
  227. return nil
  228. }
  229. return os.Chown(p, uid, gid)
  230. }
  231. // LoadIdentityMapping takes a requested username and
  232. // using the data from /etc/sub{uid,gid} ranges, creates the
  233. // proper uid and gid remapping ranges for that user/group pair
  234. func LoadIdentityMapping(name string) (IdentityMapping, error) {
  235. usr, err := LookupUser(name)
  236. if err != nil {
  237. return IdentityMapping{}, fmt.Errorf("could not get user for username %s: %v", name, err)
  238. }
  239. subuidRanges, err := lookupSubUIDRanges(usr)
  240. if err != nil {
  241. return IdentityMapping{}, err
  242. }
  243. subgidRanges, err := lookupSubGIDRanges(usr)
  244. if err != nil {
  245. return IdentityMapping{}, err
  246. }
  247. return IdentityMapping{
  248. UIDMaps: subuidRanges,
  249. GIDMaps: subgidRanges,
  250. }, nil
  251. }
  252. func lookupSubUIDRanges(usr user.User) ([]IDMap, error) {
  253. rangeList, err := parseSubuid(strconv.Itoa(usr.Uid))
  254. if err != nil {
  255. return nil, err
  256. }
  257. if len(rangeList) == 0 {
  258. rangeList, err = parseSubuid(usr.Name)
  259. if err != nil {
  260. return nil, err
  261. }
  262. }
  263. if len(rangeList) == 0 {
  264. return nil, fmt.Errorf("no subuid ranges found for user %q", usr.Name)
  265. }
  266. return createIDMap(rangeList), nil
  267. }
  268. func lookupSubGIDRanges(usr user.User) ([]IDMap, error) {
  269. rangeList, err := parseSubgid(strconv.Itoa(usr.Uid))
  270. if err != nil {
  271. return nil, err
  272. }
  273. if len(rangeList) == 0 {
  274. rangeList, err = parseSubgid(usr.Name)
  275. if err != nil {
  276. return nil, err
  277. }
  278. }
  279. if len(rangeList) == 0 {
  280. return nil, fmt.Errorf("no subgid ranges found for user %q", usr.Name)
  281. }
  282. return createIDMap(rangeList), nil
  283. }