idtools_unix.go 8.2 KB

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