github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/idtools/idtools.go (about) 1 package idtools // import "github.com/demonoid81/moby/pkg/idtools" 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "strconv" 8 "strings" 9 ) 10 11 // IDMap contains a single entry for user namespace range remapping. An array 12 // of IDMap entries represents the structure that will be provided to the Linux 13 // kernel for creating a user namespace. 14 type IDMap struct { 15 ContainerID int `json:"container_id"` 16 HostID int `json:"host_id"` 17 Size int `json:"size"` 18 } 19 20 type subIDRange struct { 21 Start int 22 Length int 23 } 24 25 type ranges []subIDRange 26 27 func (e ranges) Len() int { return len(e) } 28 func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } 29 func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } 30 31 const ( 32 subuidFileName = "/etc/subuid" 33 subgidFileName = "/etc/subgid" 34 ) 35 36 // MkdirAllAndChown creates a directory (include any along the path) and then modifies 37 // ownership to the requested uid/gid. If the directory already exists, this 38 // function will still change ownership to the requested uid/gid pair. 39 func MkdirAllAndChown(path string, mode os.FileMode, owner Identity) error { 40 return mkdirAs(path, mode, owner, true, true) 41 } 42 43 // MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. 44 // If the directory already exists, this function still changes ownership. 45 // Note that unlike os.Mkdir(), this function does not return IsExist error 46 // in case path already exists. 47 func MkdirAndChown(path string, mode os.FileMode, owner Identity) error { 48 return mkdirAs(path, mode, owner, false, true) 49 } 50 51 // MkdirAllAndChownNew creates a directory (include any along the path) and then modifies 52 // ownership ONLY of newly created directories to the requested uid/gid. If the 53 // directories along the path exist, no change of ownership will be performed 54 func MkdirAllAndChownNew(path string, mode os.FileMode, owner Identity) error { 55 return mkdirAs(path, mode, owner, true, false) 56 } 57 58 // GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. 59 // If the maps are empty, then the root uid/gid will default to "real" 0/0 60 func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { 61 uid, err := toHost(0, uidMap) 62 if err != nil { 63 return -1, -1, err 64 } 65 gid, err := toHost(0, gidMap) 66 if err != nil { 67 return -1, -1, err 68 } 69 return uid, gid, nil 70 } 71 72 // toContainer takes an id mapping, and uses it to translate a 73 // host ID to the remapped ID. If no map is provided, then the translation 74 // assumes a 1-to-1 mapping and returns the passed in id 75 func toContainer(hostID int, idMap []IDMap) (int, error) { 76 if idMap == nil { 77 return hostID, nil 78 } 79 for _, m := range idMap { 80 if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { 81 contID := m.ContainerID + (hostID - m.HostID) 82 return contID, nil 83 } 84 } 85 return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) 86 } 87 88 // toHost takes an id mapping and a remapped ID, and translates the 89 // ID to the mapped host ID. If no map is provided, then the translation 90 // assumes a 1-to-1 mapping and returns the passed in id # 91 func toHost(contID int, idMap []IDMap) (int, error) { 92 if idMap == nil { 93 return contID, nil 94 } 95 for _, m := range idMap { 96 if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { 97 hostID := m.HostID + (contID - m.ContainerID) 98 return hostID, nil 99 } 100 } 101 return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) 102 } 103 104 // Identity is either a UID and GID pair or a SID (but not both) 105 type Identity struct { 106 UID int 107 GID int 108 SID string 109 } 110 111 // IdentityMapping contains a mappings of UIDs and GIDs 112 type IdentityMapping struct { 113 uids []IDMap 114 gids []IDMap 115 } 116 117 // NewIdentityMapping 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 NewIdentityMapping(username, groupname string) (*IdentityMapping, 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 &IdentityMapping{ 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) *IdentityMapping { 145 return &IdentityMapping{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 *IdentityMapping) RootPair() Identity { 152 uid, gid, _ := GetRootUIDGID(i.uids, i.gids) 153 return Identity{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 *IdentityMapping) ToHost(pair Identity) (Identity, 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 *IdentityMapping) ToContainer(pair Identity) (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 *IdentityMapping) 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 *IdentityMapping) 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 *IdentityMapping) GIDs() []IDMap { 199 return i.gids 200 } 201 202 func createIDMap(subidRanges ranges) []IDMap { 203 idMap := []IDMap{} 204 205 containerID := 0 206 for _, idrange := range subidRanges { 207 idMap = append(idMap, IDMap{ 208 ContainerID: containerID, 209 HostID: idrange.Start, 210 Size: idrange.Length, 211 }) 212 containerID = containerID + idrange.Length 213 } 214 return idMap 215 } 216 217 func parseSubuid(username string) (ranges, error) { 218 return parseSubidFile(subuidFileName, username) 219 } 220 221 func parseSubgid(username string) (ranges, error) { 222 return parseSubidFile(subgidFileName, username) 223 } 224 225 // parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid) 226 // and return all found ranges for a specified username. If the special value 227 // "ALL" is supplied for username, then all ranges in the file will be returned 228 func parseSubidFile(path, username string) (ranges, error) { 229 var rangeList ranges 230 231 subidFile, err := os.Open(path) 232 if err != nil { 233 return rangeList, err 234 } 235 defer subidFile.Close() 236 237 s := bufio.NewScanner(subidFile) 238 for s.Scan() { 239 text := strings.TrimSpace(s.Text()) 240 if text == "" || strings.HasPrefix(text, "#") { 241 continue 242 } 243 parts := strings.Split(text, ":") 244 if len(parts) != 3 { 245 return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) 246 } 247 if parts[0] == username || username == "ALL" { 248 startid, err := strconv.Atoi(parts[1]) 249 if err != nil { 250 return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) 251 } 252 length, err := strconv.Atoi(parts[2]) 253 if err != nil { 254 return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) 255 } 256 rangeList = append(rangeList, subIDRange{startid, length}) 257 } 258 } 259 260 return rangeList, s.Err() 261 }