github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/pkg/idtools/idtools.go (about) 1 package idtools 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "sort" 8 "strconv" 9 "strings" 10 ) 11 12 // IDMap contains a single entry for user namespace range remapping. An array 13 // of IDMap entries represents the structure that will be provided to the Linux 14 // kernel for creating a user namespace. 15 type IDMap struct { 16 ContainerID int `json:"container_id"` 17 HostID int `json:"host_id"` 18 Size int `json:"size"` 19 } 20 21 type subIDRange struct { 22 Start int 23 Length int 24 } 25 26 type ranges []subIDRange 27 28 func (e ranges) Len() int { return len(e) } 29 func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } 30 func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } 31 32 const ( 33 subuidFileName string = "/etc/subuid" 34 subgidFileName string = "/etc/subgid" 35 ) 36 37 // MkdirAllAndChown creates a directory (include any along the path) and then modifies 38 // ownership to the requested uid/gid. If the directory already exists, this 39 // function will still change ownership to the requested uid/gid pair. 40 func MkdirAllAndChown(path string, mode os.FileMode, owner IDPair) error { 41 return mkdirAs(path, mode, owner.UID, owner.GID, true, true) 42 } 43 44 // MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. 45 // If the directory already exists, this function still changes ownership. 46 // Note that unlike os.Mkdir(), this function does not return IsExist error 47 // in case path already exists. 48 func MkdirAndChown(path string, mode os.FileMode, owner IDPair) error { 49 return mkdirAs(path, mode, owner.UID, owner.GID, false, true) 50 } 51 52 // MkdirAllAndChownNew creates a directory (include any along the path) and then modifies 53 // ownership ONLY of newly created directories to the requested uid/gid. If the 54 // directories along the path exist, no change of ownership will be performed 55 func MkdirAllAndChownNew(path string, mode os.FileMode, owner IDPair) error { 56 return mkdirAs(path, mode, owner.UID, owner.GID, true, false) 57 } 58 59 // GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. 60 // If the maps are empty, then the root uid/gid will default to "real" 0/0 61 func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { 62 uid, err := toHost(0, uidMap) 63 if err != nil { 64 return -1, -1, err 65 } 66 gid, err := toHost(0, gidMap) 67 if err != nil { 68 return -1, -1, err 69 } 70 return uid, gid, nil 71 } 72 73 // toContainer takes an id mapping, and uses it to translate a 74 // host ID to the remapped ID. If no map is provided, then the translation 75 // assumes a 1-to-1 mapping and returns the passed in id 76 func toContainer(hostID int, idMap []IDMap) (int, error) { 77 if idMap == nil { 78 return hostID, nil 79 } 80 for _, m := range idMap { 81 if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { 82 contID := m.ContainerID + (hostID - m.HostID) 83 return contID, nil 84 } 85 } 86 return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) 87 } 88 89 // toHost takes an id mapping and a remapped ID, and translates the 90 // ID to the mapped host ID. If no map is provided, then the translation 91 // assumes a 1-to-1 mapping and returns the passed in id # 92 func toHost(contID int, idMap []IDMap) (int, error) { 93 if idMap == nil { 94 return contID, nil 95 } 96 for _, m := range idMap { 97 if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { 98 hostID := m.HostID + (contID - m.ContainerID) 99 return hostID, nil 100 } 101 } 102 return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) 103 } 104 105 // IDPair is a UID and GID pair 106 type IDPair struct { 107 UID int 108 GID int 109 } 110 111 // IDMappings contains a mappings of UIDs and GIDs 112 type IDMappings struct { 113 uids []IDMap 114 gids []IDMap 115 } 116 117 // NewIDMappings takes a requested user and group name and 118 // using the data from /etc/sub{uid,gid} ranges, creates the 119 // proper uid and gid remapping ranges for that user/group pair 120 func NewIDMappings(username, groupname string) (*IDMappings, error) { 121 subuidRanges, err := parseSubuid(username) 122 if err != nil { 123 return nil, err 124 } 125 subgidRanges, err := parseSubgid(groupname) 126 if err != nil { 127 return nil, err 128 } 129 if len(subuidRanges) == 0 { 130 return nil, fmt.Errorf("No subuid ranges found for user %q", username) 131 } 132 if len(subgidRanges) == 0 { 133 return nil, fmt.Errorf("No subgid ranges found for group %q", groupname) 134 } 135 136 return &IDMappings{ 137 uids: createIDMap(subuidRanges), 138 gids: createIDMap(subgidRanges), 139 }, nil 140 } 141 142 // NewIDMappingsFromMaps creates a new mapping from two slices 143 // Deprecated: this is a temporary shim while transitioning to IDMapping 144 func NewIDMappingsFromMaps(uids []IDMap, gids []IDMap) *IDMappings { 145 return &IDMappings{uids: uids, gids: gids} 146 } 147 148 // RootPair returns a uid and gid pair for the root user. The error is ignored 149 // because a root user always exists, and the defaults are correct when the uid 150 // and gid maps are empty. 151 func (i *IDMappings) RootPair() IDPair { 152 uid, gid, _ := GetRootUIDGID(i.uids, i.gids) 153 return IDPair{UID: uid, GID: gid} 154 } 155 156 // ToHost returns the host UID and GID for the container uid, gid. 157 // Remapping is only performed if the ids aren't already the remapped root ids 158 func (i *IDMappings) ToHost(pair IDPair) (IDPair, error) { 159 var err error 160 target := i.RootPair() 161 162 if pair.UID != target.UID { 163 target.UID, err = toHost(pair.UID, i.uids) 164 if err != nil { 165 return target, err 166 } 167 } 168 169 if pair.GID != target.GID { 170 target.GID, err = toHost(pair.GID, i.gids) 171 } 172 return target, err 173 } 174 175 // ToContainer returns the container UID and GID for the host uid and gid 176 func (i *IDMappings) ToContainer(pair IDPair) (int, int, error) { 177 uid, err := toContainer(pair.UID, i.uids) 178 if err != nil { 179 return -1, -1, err 180 } 181 gid, err := toContainer(pair.GID, i.gids) 182 return uid, gid, err 183 } 184 185 // Empty returns true if there are no id mappings 186 func (i *IDMappings) Empty() bool { 187 return len(i.uids) == 0 && len(i.gids) == 0 188 } 189 190 // UIDs return the UID mapping 191 // TODO: remove this once everything has been refactored to use pairs 192 func (i *IDMappings) UIDs() []IDMap { 193 return i.uids 194 } 195 196 // GIDs return the UID mapping 197 // TODO: remove this once everything has been refactored to use pairs 198 func (i *IDMappings) GIDs() []IDMap { 199 return i.gids 200 } 201 202 func createIDMap(subidRanges ranges) []IDMap { 203 idMap := []IDMap{} 204 205 // sort the ranges by lowest ID first 206 sort.Sort(subidRanges) 207 containerID := 0 208 for _, idrange := range subidRanges { 209 idMap = append(idMap, IDMap{ 210 ContainerID: containerID, 211 HostID: idrange.Start, 212 Size: idrange.Length, 213 }) 214 containerID = containerID + idrange.Length 215 } 216 return idMap 217 } 218 219 func parseSubuid(username string) (ranges, error) { 220 return parseSubidFile(subuidFileName, username) 221 } 222 223 func parseSubgid(username string) (ranges, error) { 224 return parseSubidFile(subgidFileName, username) 225 } 226 227 // parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid) 228 // and return all found ranges for a specified username. If the special value 229 // "ALL" is supplied for username, then all ranges in the file will be returned 230 func parseSubidFile(path, username string) (ranges, error) { 231 var rangeList ranges 232 233 subidFile, err := os.Open(path) 234 if err != nil { 235 return rangeList, err 236 } 237 defer subidFile.Close() 238 239 s := bufio.NewScanner(subidFile) 240 for s.Scan() { 241 if err := s.Err(); err != nil { 242 return rangeList, err 243 } 244 245 text := strings.TrimSpace(s.Text()) 246 if text == "" || strings.HasPrefix(text, "#") { 247 continue 248 } 249 parts := strings.Split(text, ":") 250 if len(parts) != 3 { 251 return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) 252 } 253 if parts[0] == username || username == "ALL" { 254 startid, err := strconv.Atoi(parts[1]) 255 if err != nil { 256 return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) 257 } 258 length, err := strconv.Atoi(parts[2]) 259 if err != nil { 260 return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) 261 } 262 rangeList = append(rangeList, subIDRange{startid, length}) 263 } 264 } 265 return rangeList, nil 266 }