idtools_unix.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. "path/filepath"
  10. "strconv"
  11. "sync"
  12. "syscall"
  13. "github.com/docker/docker/pkg/system"
  14. "github.com/opencontainers/runc/libcontainer/user"
  15. "github.com/pkg/errors"
  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. // make an array containing the original path asked for, plus (for mkAll == true)
  23. // all path components leading up to the complete path that don't exist before we MkdirAll
  24. // so that we can chown all of them properly at the end. If chownExisting is false, we won't
  25. // chown the full directory path if it exists
  26. var paths []string
  27. path, err := filepath.Abs(path)
  28. if err != nil {
  29. return err
  30. }
  31. stat, err := system.Stat(path)
  32. if err == nil {
  33. if !stat.IsDir() {
  34. return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR}
  35. }
  36. if !chownExisting {
  37. return nil
  38. }
  39. // short-circuit--we were called with an existing directory and chown was requested
  40. return setPermissions(path, mode, owner.UID, owner.GID, stat)
  41. }
  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 := system.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. fileMode := os.FileMode(statInfo.Mode())
  83. permBits := fileMode.Perm()
  84. return accessible(statInfo.UID() == uint32(pair.UID),
  85. statInfo.GID() == uint32(pair.GID), permBits)
  86. }
  87. func accessible(isOwner, isGroup bool, perms os.FileMode) bool {
  88. if isOwner && (perms&0100 == 0100) {
  89. return true
  90. }
  91. if isGroup && (perms&0010 == 0010) {
  92. return true
  93. }
  94. if perms&0001 == 0001 {
  95. return true
  96. }
  97. return false
  98. }
  99. // LookupUser uses traditional local system files lookup (from libcontainer/user) on a username,
  100. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  101. func LookupUser(name string) (user.User, error) {
  102. // first try a local system files lookup using existing capabilities
  103. usr, err := user.LookupUser(name)
  104. if err == nil {
  105. return usr, nil
  106. }
  107. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  108. usr, err = getentUser(name)
  109. if err != nil {
  110. return user.User{}, err
  111. }
  112. return usr, nil
  113. }
  114. // LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid,
  115. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  116. func LookupUID(uid int) (user.User, error) {
  117. // first try a local system files lookup using existing capabilities
  118. usr, err := user.LookupUid(uid)
  119. if err == nil {
  120. return usr, nil
  121. }
  122. // local files lookup failed; attempt to call `getent` to query configured passwd dbs
  123. return getentUser(strconv.Itoa(uid))
  124. }
  125. func getentUser(name string) (user.User, error) {
  126. reader, err := callGetent("passwd", name)
  127. if err != nil {
  128. return user.User{}, err
  129. }
  130. users, err := user.ParsePasswd(reader)
  131. if err != nil {
  132. return user.User{}, err
  133. }
  134. if len(users) == 0 {
  135. return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", name)
  136. }
  137. return users[0], nil
  138. }
  139. // LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name,
  140. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  141. func LookupGroup(name string) (user.Group, error) {
  142. // first try a local system files lookup using existing capabilities
  143. group, err := user.LookupGroup(name)
  144. if err == nil {
  145. return group, nil
  146. }
  147. // local files lookup failed; attempt to call `getent` to query configured group dbs
  148. return getentGroup(name)
  149. }
  150. // LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID,
  151. // followed by a call to `getent` for supporting host configured non-files passwd and group dbs
  152. func LookupGID(gid int) (user.Group, error) {
  153. // first try a local system files lookup using existing capabilities
  154. group, err := user.LookupGid(gid)
  155. if err == nil {
  156. return group, nil
  157. }
  158. // local files lookup failed; attempt to call `getent` to query configured group dbs
  159. return getentGroup(strconv.Itoa(gid))
  160. }
  161. func getentGroup(name string) (user.Group, error) {
  162. reader, err := callGetent("group", name)
  163. if err != nil {
  164. return user.Group{}, err
  165. }
  166. groups, err := user.ParseGroup(reader)
  167. if err != nil {
  168. return user.Group{}, err
  169. }
  170. if len(groups) == 0 {
  171. return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", name)
  172. }
  173. return groups[0], nil
  174. }
  175. func callGetent(database, key string) (io.Reader, error) {
  176. entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") })
  177. // if no `getent` command on host, can't do anything else
  178. if getentCmd == "" {
  179. return nil, fmt.Errorf("unable to find getent command")
  180. }
  181. out, err := execCmd(getentCmd, database, key)
  182. if err != nil {
  183. exitCode, errC := system.GetExitCode(err)
  184. if errC != nil {
  185. return nil, err
  186. }
  187. switch exitCode {
  188. case 1:
  189. return nil, fmt.Errorf("getent reported invalid parameters/database unknown")
  190. case 2:
  191. return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, database)
  192. case 3:
  193. return nil, fmt.Errorf("getent database doesn't support enumeration")
  194. default:
  195. return nil, err
  196. }
  197. }
  198. return bytes.NewReader(out), nil
  199. }
  200. // setPermissions performs a chown/chmod only if the uid/gid don't match what's requested
  201. // 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
  202. // dir is on an NFS share, so don't call chown unless we absolutely must.
  203. // Likewise for setting permissions.
  204. func setPermissions(p string, mode os.FileMode, uid, gid int, stat *system.StatT) error {
  205. if stat == nil {
  206. var err error
  207. stat, err = system.Stat(p)
  208. if err != nil {
  209. return err
  210. }
  211. }
  212. if os.FileMode(stat.Mode()).Perm() != mode.Perm() {
  213. if err := os.Chmod(p, mode.Perm()); err != nil {
  214. return err
  215. }
  216. }
  217. if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) {
  218. return nil
  219. }
  220. return os.Chown(p, uid, gid)
  221. }
  222. // NewIdentityMapping takes a requested username and
  223. // using the data from /etc/sub{uid,gid} ranges, creates the
  224. // proper uid and gid remapping ranges for that user/group pair
  225. //
  226. // Deprecated: Use LoadIdentityMapping.
  227. func NewIdentityMapping(name string) (*IdentityMapping, error) {
  228. m, err := LoadIdentityMapping(name)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &m, err
  233. }
  234. // LoadIdentityMapping takes a requested username and
  235. // using the data from /etc/sub{uid,gid} ranges, creates the
  236. // proper uid and gid remapping ranges for that user/group pair
  237. func LoadIdentityMapping(name string) (IdentityMapping, error) {
  238. usr, err := LookupUser(name)
  239. if err != nil {
  240. return IdentityMapping{}, fmt.Errorf("Could not get user for username %s: %v", name, err)
  241. }
  242. subuidRanges, err := lookupSubUIDRanges(usr)
  243. if err != nil {
  244. return IdentityMapping{}, err
  245. }
  246. subgidRanges, err := lookupSubGIDRanges(usr)
  247. if err != nil {
  248. return IdentityMapping{}, err
  249. }
  250. return IdentityMapping{
  251. UIDMaps: subuidRanges,
  252. GIDMaps: subgidRanges,
  253. }, nil
  254. }
  255. func lookupSubUIDRanges(usr user.User) ([]IDMap, error) {
  256. rangeList, err := parseSubuid(strconv.Itoa(usr.Uid))
  257. if err != nil {
  258. return nil, err
  259. }
  260. if len(rangeList) == 0 {
  261. rangeList, err = parseSubuid(usr.Name)
  262. if err != nil {
  263. return nil, err
  264. }
  265. }
  266. if len(rangeList) == 0 {
  267. return nil, errors.Errorf("no subuid ranges found for user %q", usr.Name)
  268. }
  269. return createIDMap(rangeList), nil
  270. }
  271. func lookupSubGIDRanges(usr user.User) ([]IDMap, error) {
  272. rangeList, err := parseSubgid(strconv.Itoa(usr.Uid))
  273. if err != nil {
  274. return nil, err
  275. }
  276. if len(rangeList) == 0 {
  277. rangeList, err = parseSubgid(usr.Name)
  278. if err != nil {
  279. return nil, err
  280. }
  281. }
  282. if len(rangeList) == 0 {
  283. return nil, errors.Errorf("no subgid ranges found for user %q", usr.Name)
  284. }
  285. return createIDMap(rangeList), nil
  286. }