idtools_unix.go 8.6 KB

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