idtools.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package idtools // import "github.com/docker/docker/pkg/idtools"
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. // IDMap contains a single entry for user namespace range remapping. An array
  10. // of IDMap entries represents the structure that will be provided to the Linux
  11. // kernel for creating a user namespace.
  12. type IDMap struct {
  13. ContainerID int `json:"container_id"`
  14. HostID int `json:"host_id"`
  15. Size int `json:"size"`
  16. }
  17. type subIDRange struct {
  18. Start int
  19. Length int
  20. }
  21. type ranges []subIDRange
  22. func (e ranges) Len() int { return len(e) }
  23. func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
  24. func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start }
  25. const (
  26. subuidFileName = "/etc/subuid"
  27. subgidFileName = "/etc/subgid"
  28. )
  29. // MkdirAllAndChown creates a directory (include any along the path) and then modifies
  30. // ownership to the requested uid/gid. If the directory already exists, this
  31. // function will still change ownership and permissions.
  32. func MkdirAllAndChown(path string, mode os.FileMode, owner Identity) error {
  33. return mkdirAs(path, mode, owner, true, true)
  34. }
  35. // MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid.
  36. // If the directory already exists, this function still changes ownership and permissions.
  37. // Note that unlike os.Mkdir(), this function does not return IsExist error
  38. // in case path already exists.
  39. func MkdirAndChown(path string, mode os.FileMode, owner Identity) error {
  40. return mkdirAs(path, mode, owner, false, true)
  41. }
  42. // MkdirAllAndChownNew creates a directory (include any along the path) and then modifies
  43. // ownership ONLY of newly created directories to the requested uid/gid. If the
  44. // directories along the path exist, no change of ownership or permissions will be performed
  45. func MkdirAllAndChownNew(path string, mode os.FileMode, owner Identity) error {
  46. return mkdirAs(path, mode, owner, true, false)
  47. }
  48. // GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps.
  49. // If the maps are empty, then the root uid/gid will default to "real" 0/0
  50. func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) {
  51. uid, err := toHost(0, uidMap)
  52. if err != nil {
  53. return -1, -1, err
  54. }
  55. gid, err := toHost(0, gidMap)
  56. if err != nil {
  57. return -1, -1, err
  58. }
  59. return uid, gid, nil
  60. }
  61. // toContainer takes an id mapping, and uses it to translate a
  62. // host ID to the remapped ID. If no map is provided, then the translation
  63. // assumes a 1-to-1 mapping and returns the passed in id
  64. func toContainer(hostID int, idMap []IDMap) (int, error) {
  65. if idMap == nil {
  66. return hostID, nil
  67. }
  68. for _, m := range idMap {
  69. if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) {
  70. contID := m.ContainerID + (hostID - m.HostID)
  71. return contID, nil
  72. }
  73. }
  74. return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID)
  75. }
  76. // toHost takes an id mapping and a remapped ID, and translates the
  77. // ID to the mapped host ID. If no map is provided, then the translation
  78. // assumes a 1-to-1 mapping and returns the passed in id #
  79. func toHost(contID int, idMap []IDMap) (int, error) {
  80. if idMap == nil {
  81. return contID, nil
  82. }
  83. for _, m := range idMap {
  84. if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) {
  85. hostID := m.HostID + (contID - m.ContainerID)
  86. return hostID, nil
  87. }
  88. }
  89. return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID)
  90. }
  91. // Identity is either a UID and GID pair or a SID (but not both)
  92. type Identity struct {
  93. UID int
  94. GID int
  95. SID string
  96. }
  97. // Chown changes the numeric uid and gid of the named file to id.UID and id.GID.
  98. func (id Identity) Chown(name string) error {
  99. return os.Chown(name, id.UID, id.GID)
  100. }
  101. // IdentityMapping contains a mappings of UIDs and GIDs.
  102. // The zero value represents an empty mapping.
  103. type IdentityMapping struct {
  104. UIDMaps []IDMap `json:"UIDMaps"`
  105. GIDMaps []IDMap `json:"GIDMaps"`
  106. }
  107. // RootPair returns a uid and gid pair for the root user. The error is ignored
  108. // because a root user always exists, and the defaults are correct when the uid
  109. // and gid maps are empty.
  110. func (i IdentityMapping) RootPair() Identity {
  111. uid, gid, _ := GetRootUIDGID(i.UIDMaps, i.GIDMaps)
  112. return Identity{UID: uid, GID: gid}
  113. }
  114. // ToHost returns the host UID and GID for the container uid, gid.
  115. // Remapping is only performed if the ids aren't already the remapped root ids
  116. func (i IdentityMapping) ToHost(pair Identity) (Identity, error) {
  117. var err error
  118. target := i.RootPair()
  119. if pair.UID != target.UID {
  120. target.UID, err = toHost(pair.UID, i.UIDMaps)
  121. if err != nil {
  122. return target, err
  123. }
  124. }
  125. if pair.GID != target.GID {
  126. target.GID, err = toHost(pair.GID, i.GIDMaps)
  127. }
  128. return target, err
  129. }
  130. // ToContainer returns the container UID and GID for the host uid and gid
  131. func (i IdentityMapping) ToContainer(pair Identity) (int, int, error) {
  132. uid, err := toContainer(pair.UID, i.UIDMaps)
  133. if err != nil {
  134. return -1, -1, err
  135. }
  136. gid, err := toContainer(pair.GID, i.GIDMaps)
  137. return uid, gid, err
  138. }
  139. // Empty returns true if there are no id mappings
  140. func (i IdentityMapping) Empty() bool {
  141. return len(i.UIDMaps) == 0 && len(i.GIDMaps) == 0
  142. }
  143. func createIDMap(subidRanges ranges) []IDMap {
  144. idMap := []IDMap{}
  145. containerID := 0
  146. for _, idrange := range subidRanges {
  147. idMap = append(idMap, IDMap{
  148. ContainerID: containerID,
  149. HostID: idrange.Start,
  150. Size: idrange.Length,
  151. })
  152. containerID = containerID + idrange.Length
  153. }
  154. return idMap
  155. }
  156. func parseSubuid(username string) (ranges, error) {
  157. return parseSubidFile(subuidFileName, username)
  158. }
  159. func parseSubgid(username string) (ranges, error) {
  160. return parseSubidFile(subgidFileName, username)
  161. }
  162. // parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid)
  163. // and return all found ranges for a specified username. If the special value
  164. // "ALL" is supplied for username, then all ranges in the file will be returned
  165. func parseSubidFile(path, username string) (ranges, error) {
  166. var rangeList ranges
  167. subidFile, err := os.Open(path)
  168. if err != nil {
  169. return rangeList, err
  170. }
  171. defer subidFile.Close()
  172. s := bufio.NewScanner(subidFile)
  173. for s.Scan() {
  174. text := strings.TrimSpace(s.Text())
  175. if text == "" || strings.HasPrefix(text, "#") {
  176. continue
  177. }
  178. parts := strings.Split(text, ":")
  179. if len(parts) != 3 {
  180. return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path)
  181. }
  182. if parts[0] == username || username == "ALL" {
  183. startid, err := strconv.Atoi(parts[1])
  184. if err != nil {
  185. return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err)
  186. }
  187. length, err := strconv.Atoi(parts[2])
  188. if err != nil {
  189. return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err)
  190. }
  191. rangeList = append(rangeList, subIDRange{startid, length})
  192. }
  193. }
  194. return rangeList, s.Err()
  195. }
  196. // CurrentIdentity returns the identity of the current process
  197. func CurrentIdentity() Identity {
  198. return Identity{UID: os.Getuid(), GID: os.Getegid()}
  199. }