diff --git a/vendor.mod b/vendor.mod index 8c2ecc54343c..a1bf702a647a 100644 --- a/vendor.mod +++ b/vendor.mod @@ -89,7 +89,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/klauspost/compress v1.20.2 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/moby/sys/user v0.4.1 // indirect + github.com/moby/sys/user v0.5.1 // indirect github.com/moby/sys/userns v0.2.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/prometheus/client_golang v1.22.0 // indirect diff --git a/vendor.sum b/vendor.sum index 5e0a24bdb5cd..f13bf3fd84ff 100644 --- a/vendor.sum +++ b/vendor.sum @@ -110,8 +110,8 @@ github.com/moby/sys/signal v0.7.1 h1:PrQxdvxcGijdo6UXXo/lU/TvHUWyPhj7UOpSo8tuvk0 github.com/moby/sys/signal v0.7.1/go.mod h1:Se1VGehYokAkrSQwL4tDzHvETwUZlnY7S5XtQ50mQp8= github.com/moby/sys/symlink v0.3.0 h1:GZX89mEZ9u53f97npBy4Rc3vJKj7JBDj/PN2I22GrNU= github.com/moby/sys/symlink v0.3.0/go.mod h1:3eNdhduHmYPcgsJtZXW1W4XUJdZGBIkttZ8xKqPUJq0= -github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0= -github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y= +github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0= +github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow= github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8= github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= diff --git a/vendor/github.com/moby/sys/user/idtools.go b/vendor/github.com/moby/sys/user/idtools.go index 595b7a927263..147815311166 100644 --- a/vendor/github.com/moby/sys/user/idtools.go +++ b/vendor/github.com/moby/sys/user/idtools.go @@ -12,37 +12,39 @@ type mkdirOptions struct { onlyNew bool } -// WithOnlyNew is an option for MkdirAllAndChown that will only change ownership and permissions -// on newly created directories. If the directory already exists, it will not be modified +// WithOnlyNew configures [MkdirAllAndChown] and [MkdirAndChown] to leave +// the requested directory unchanged if it already exists. Newly created +// directories are still assigned the requested ownership and permissions. func WithOnlyNew(o *mkdirOptions) { o.onlyNew = true } -// MkdirAllAndChown creates a directory (include any along the path) and then modifies -// ownership to the requested uid/gid. By default, if the directory already exists, this -// function will still change ownership and permissions. If WithOnlyNew is passed as an -// option, then only the newly created directories will have ownership and permissions changed. +// MkdirAllAndChown creates a directory named path, along with any necessary +// parents, and applies the requested ownership and permission bits to all +// directories it creates. +// +// If path already exists as a directory, its ownership and permission bits +// are updated unless [WithOnlyNew] is specified. Existing parent directories +// are not modified. +// +// MkdirAllAndChown is similar to [os.MkdirAll], but also applies ownership and +// reapplies the requested permission bits after creation, so the resulting +// permissions are not affected by the process umask. func MkdirAllAndChown(path string, mode os.FileMode, uid, gid int, opts ...MkdirOpt) error { - var options mkdirOptions - for _, opt := range opts { - opt(&options) - } - - return mkdirAs(path, mode, uid, gid, true, options.onlyNew) + return mkdirAs(path, mode, uid, gid, true, opts...) } -// MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. -// By default, if the directory already exists, this function still changes ownership and permissions. -// If WithOnlyNew is passed as an option, then only the newly created directory will have ownership -// and permissions changed. -// Note that unlike os.Mkdir(), this function does not return IsExist error -// in case path already exists. +// MkdirAndChown creates a directory named path and applies the requested +// ownership and permission bits. +// +// If path already exists as a directory, its ownership and permission bits +// are updated unless [WithOnlyNew] is specified. +// +// MkdirAndChown is similar to [os.Mkdir], but returns nil if path already +// exists as a directory. The resulting permission bits are not affected by +// the process umask. func MkdirAndChown(path string, mode os.FileMode, uid, gid int, opts ...MkdirOpt) error { - var options mkdirOptions - for _, opt := range opts { - opt(&options) - } - return mkdirAs(path, mode, uid, gid, false, options.onlyNew) + return mkdirAs(path, mode, uid, gid, false, opts...) } // getRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. @@ -106,22 +108,14 @@ func (i IdentityMapping) RootPair() (int, int) { return uid, gid } -// ToHost returns the host UID and GID for the container uid, gid. -// Remapping is only performed if the ids aren't already the remapped root ids +// ToHost returns the host UID and GID for the container uid and gid. +// An empty mapping is treated as identity. func (i IdentityMapping) ToHost(uid, gid int) (int, int, error) { - var err error - ruid, rgid := i.RootPair() - - if uid != ruid { - ruid, err = toHost(uid, i.UIDMaps) - if err != nil { - return ruid, rgid, err - } - } - - if gid != rgid { - rgid, err = toHost(gid, i.GIDMaps) + ruid, err := toHost(uid, i.UIDMaps) + if err != nil { + return -1, -1, err } + rgid, err := toHost(gid, i.GIDMaps) return ruid, rgid, err } diff --git a/vendor/github.com/moby/sys/user/idtools_unix.go b/vendor/github.com/moby/sys/user/idtools_unix.go index 4e39d2446b23..929aaa07a7e9 100644 --- a/vendor/github.com/moby/sys/user/idtools_unix.go +++ b/vendor/github.com/moby/sys/user/idtools_unix.go @@ -3,6 +3,7 @@ package user import ( + "errors" "fmt" "os" "path/filepath" @@ -10,57 +11,59 @@ import ( "syscall" ) -func mkdirAs(path string, mode os.FileMode, uid, gid int, mkAll, onlyNew bool) error { +func mkdirAs(path string, mode os.FileMode, uid, gid int, mkAll bool, opts ...MkdirOpt) error { + var options mkdirOptions + for _, opt := range opts { + opt(&options) + } + path, err := filepath.Abs(path) if err != nil { return err } - stat, err := os.Stat(path) - if err == nil { + stat, statErr := os.Stat(path) + if statErr == nil { if !stat.IsDir() { return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} } - if onlyNew { + // The requested directory already exists. Leave it unchanged when only + // newly created directories should receive the requested metadata. + if options.onlyNew { return nil } - - // short-circuit -- we were called with an existing directory and chown was requested return setPermissions(path, mode, uid, gid, stat) } - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If onlyNew is true, we won't - // chown the full directory path if it exists - var paths []string - if os.IsNotExist(err) { - paths = append(paths, path) + // Track the requested directory and any parent directories created by + // Mkdir/MkdirAll to set their ownership and permissions afterward. + var createdDirs []string + if errors.Is(statErr, os.ErrNotExist) { + createdDirs = append(createdDirs, path) } if mkAll { - // walk back to "/" looking for directories which do not exist - // and add them to the paths array for chown after creation - dirPath := path - for { - dirPath = filepath.Dir(dirPath) - if dirPath == "/" { - break - } - if _, err = os.Stat(dirPath); os.IsNotExist(err) { - paths = append(paths, dirPath) + if errors.Is(statErr, os.ErrNotExist) { + // Walk back to "/" looking for directories which do not exist + // and add them to the paths array for chown after creation. + // Stop at the first existing directory. + for p := filepath.Dir(path); p != "/"; p = filepath.Dir(p) { + if _, err := os.Stat(p); err == nil { + break + } else if errors.Is(err, os.ErrNotExist) { + createdDirs = append(createdDirs, p) + } } } - if err = os.MkdirAll(path, mode); err != nil { + if err := os.MkdirAll(path, mode); err != nil { return err } - } else if err = os.Mkdir(path, mode); err != nil { + } else if err := os.Mkdir(path, mode); err != nil { return err } - // even if it existed, we will chown the requested path + any subpaths that - // didn't exist when we called MkdirAll - for _, pathComponent := range paths { - if err = setPermissions(pathComponent, mode, uid, gid, nil); err != nil { + // Apply the requested ownership and permissions to each newly created directory. + for _, dir := range createdDirs { + if err := setPermissions(dir, mode, uid, gid, nil); err != nil { return err } } diff --git a/vendor/github.com/moby/sys/user/idtools_windows.go b/vendor/github.com/moby/sys/user/idtools_windows.go index 9de730cafbe0..3973d5593a22 100644 --- a/vendor/github.com/moby/sys/user/idtools_windows.go +++ b/vendor/github.com/moby/sys/user/idtools_windows.go @@ -2,12 +2,25 @@ package user import ( "os" + "syscall" ) -// This is currently a wrapper around [os.MkdirAll] since currently -// permissions aren't set through this path, the identity isn't utilized. -// Ownership is handled elsewhere, but in the future could be support here -// too. -func mkdirAs(path string, _ os.FileMode, _, _ int, _, _ bool) error { - return os.MkdirAll(path, 0) +// mkdirAs creates path, optionally creating any missing parent directories. +// +// On Windows this is currently a thin wrapper around os.Mkdir and +// os.MkdirAll. Unlike the Unix implementation, ownership and permission +// bits are not applied. +func mkdirAs(path string, _ os.FileMode, _, _ int, mkAll bool, _ ...MkdirOpt) error { + if mkAll { + return os.MkdirAll(path, 0) + } + stat, err := os.Stat(path) + if err == nil { + if !stat.IsDir() { + return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} + } + return nil + } + + return os.Mkdir(path, 0) } diff --git a/vendor/github.com/moby/sys/user/lookup_unix.go b/vendor/github.com/moby/sys/user/lookup_unix.go index 4540747d28fb..570793fe211c 100644 --- a/vendor/github.com/moby/sys/user/lookup_unix.go +++ b/vendor/github.com/moby/sys/user/lookup_unix.go @@ -20,7 +20,7 @@ const ( // cannot be found (or there is no /etc/passwd file on the filesystem), then // LookupUser returns an error. func LookupUser(username string) (User, error) { - return lookupUserFunc(func(u User) bool { + return lookupUserFileFilter(unixPasswdPath, func(u User) bool { return u.Name == username }) } @@ -29,21 +29,13 @@ func LookupUser(username string) (User, error) { // be found (or there is no /etc/passwd file on the filesystem), then LookupId // returns an error. func LookupUid(uid int) (User, error) { - return lookupUserFunc(func(u User) bool { + return lookupUserFileFilter(unixPasswdPath, func(u User) bool { return u.Uid == uid }) } -func lookupUserFunc(filter func(u User) bool) (User, error) { - // Get operating system-specific passwd reader-closer. - passwd, err := GetPasswd() - if err != nil { - return User{}, err - } - defer passwd.Close() - - // Get the users. - users, err := ParsePasswdFilter(passwd, filter) +func lookupUserFileFilter(path string, filter func(u User) bool) (User, error) { + users, err := ParsePasswdFileFilter(path, filter) if err != nil { return User{}, err } @@ -61,7 +53,7 @@ func lookupUserFunc(filter func(u User) bool) (User, error) { // be found (or there is no /etc/group file on the filesystem), then LookupGroup // returns an error. func LookupGroup(groupname string) (Group, error) { - return lookupGroupFunc(func(g Group) bool { + return lookupGroupFileFilter(unixGroupPath, func(g Group) bool { return g.Name == groupname }) } @@ -70,21 +62,13 @@ func LookupGroup(groupname string) (Group, error) { // be found (or there is no /etc/group file on the filesystem), then LookupGid // returns an error. func LookupGid(gid int) (Group, error) { - return lookupGroupFunc(func(g Group) bool { + return lookupGroupFileFilter(unixGroupPath, func(g Group) bool { return g.Gid == gid }) } -func lookupGroupFunc(filter func(g Group) bool) (Group, error) { - // Get operating system-specific group reader-closer. - group, err := GetGroup() - if err != nil { - return Group{}, err - } - defer group.Close() - - // Get the users. - groups, err := ParseGroupFilter(group, filter) +func lookupGroupFileFilter(path string, filter func(g Group) bool) (Group, error) { + groups, err := ParseGroupFileFilter(path, filter) if err != nil { return Group{}, err } @@ -98,18 +82,30 @@ func lookupGroupFunc(filter func(g Group) bool) (Group, error) { return groups[0], nil } +// GetPasswdPath returns the path to the system passwd file. func GetPasswdPath() (string, error) { return unixPasswdPath, nil } +// GetPasswd opens the system passwd file for reading. +// +// Unlike the file-based parsing functions, it does not restrict the file type +// or limit the amount of data that can be read. The caller is responsible for +// closing the returned reader. func GetPasswd() (io.ReadCloser, error) { return os.Open(unixPasswdPath) } +// GetGroupPath returns the path to the system group file. func GetGroupPath() (string, error) { return unixGroupPath, nil } +// GetGroup opens the system group file for reading. +// +// Unlike the file-based parsing functions, it does not restrict the file type +// or limit the amount of data that can be read. The caller is responsible for +// closing the returned reader. func GetGroup() (io.ReadCloser, error) { return os.Open(unixGroupPath) } diff --git a/vendor/github.com/moby/sys/user/user.go b/vendor/github.com/moby/sys/user/user.go index 857711ebfd21..66b4a4b48b96 100644 --- a/vendor/github.com/moby/sys/user/user.go +++ b/vendor/github.com/moby/sys/user/user.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "os" + "slices" "strconv" "strings" ) @@ -17,9 +18,9 @@ const ( ) var ( - // ErrNoPasswdEntries is returned if no matching entries were found in /etc/group. + // ErrNoPasswdEntries is returned if no matching entries were found in /etc/passwd. ErrNoPasswdEntries = errors.New("no matching entries in passwd file") - // ErrNoGroupEntries is returned if no matching entries were found in /etc/passwd. + // ErrNoGroupEntries is returned if no matching entries were found in /etc/group. ErrNoGroupEntries = errors.New("no matching entries in group file") // ErrRange is returned if a UID or GID is outside of the valid range. ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minID, maxID) @@ -56,44 +57,67 @@ type IDMap struct { Count int64 } -func parseLine(line []byte, v ...any) { - parseParts(bytes.Split(line, []byte(":")), v...) +// parseLine parses a colon-separated record into the provided fields. +// See [parseParts] for details. +func parseLine(line []byte, v ...any) bool { + return parseParts(bytes.Split(line, []byte(":")), v...) } -func parseParts(parts [][]byte, v ...any) { - if len(parts) == 0 { - return - } - - for i, p := range parts { - // Ignore cases where we don't have enough fields to populate the arguments. - // Some configuration files like to misbehave. - if len(v) <= i { - break +// parseParts parses the provided parts into the corresponding fields, +// and reports whether the record is valid. +// +// Missing fields are treated as empty. Empty string fields are accepted, +// but missing, empty, non-numeric, or out-of-range integer fields make +// the record invalid. For *int fields (UIDs and GIDs), the valid range +// is the one checked by [validateID]. +// +// This follows the behavior of glibc's passwd and group parsers, which +// skip malformed records when reading entries. +// +// See https://sources.debian.org/src/glibc/2.42-13/nss/nss_fgetent_r.c/ +// and https://sources.debian.org/src/glibc/2.42-13/nss/fgetpwent_r.c/#L150-L165 +func parseParts(parts [][]byte, fields ...any) bool { + for i, v := range fields { + var p []byte + if i < len(parts) { + p = parts[i] } // Use the type of the argument to figure out how to parse it, scanf() style. // This is legit. - switch e := v[i].(type) { + switch e := v.(type) { case *string: *e = string(p) case *int: - // "numbers", with conversion errors ignored because of some misbehaving configuration files. - *e, _ = strconv.Atoi(string(p)) + // The only *int fields are UIDs and GIDs. + n, err := parseNumeric(string(p)) + if err != nil { + return false + } + *e = n case *int64: - *e, _ = strconv.ParseInt(string(p), 10, 64) + n, err := strconv.ParseInt(string(p), 10, 64) + if err != nil { + return false + } + *e = n case *[]string: - // Comma-separated lists. - if len(p) != 0 { - *e = strings.Split(string(p), ",") - } else { - *e = []string{} + // Comma-separated lists. Like glibc, skip leading whitespace + // (but keep trailing one), and drop empty elements. + // + // See https://sources.debian.org/src/glibc/2.42-13/nss/nss_files/files-parse.c/#L278-L291 + *e = []string{} + for s := range strings.SplitSeq(string(p), ",") { + if s = strings.TrimLeft(s, " \t\n\v\f\r"); s != "" { + *e = append(*e, s) + } } default: // Someone goof'd when writing code using this function. Scream so they can hear us. panic(fmt.Sprintf("parseLine only accepts {*string, *int, *int64, *[]string} as arguments! %#v is not a pointer!", e)) } } + return true } func ParsePasswdFile(path string) ([]User, error) { @@ -105,7 +129,7 @@ func ParsePasswd(passwd io.Reader) ([]User, error) { } func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) { - passwd, err := os.Open(path) + passwd, err := openUserFile(path) if err != nil { return nil, err } @@ -124,8 +148,9 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { ) for s.Scan() { + // Skip blank lines and comments, like glibc does (see ParseGroupFilter). line := bytes.TrimSpace(s.Bytes()) - if len(line) == 0 { + if len(line) == 0 || line[0] == '#' { continue } @@ -135,7 +160,10 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { // root:x:0:0:root:/root:/bin/bash // adm:x:3:4:adm:/var/adm:/bin/false p := User{} - parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) + if !parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -194,7 +222,10 @@ func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { // root:x:0:root // adm:x:4:root,adm,daemon p := Group{} - parseLine(line, &p.Name, &p.Pass, &p.Gid, &p.List) + if !parseLine(line, &p.Name, &p.Pass, &p.Gid, &p.List) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -234,36 +265,50 @@ func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath return GetExecUser(userSpec, defaults, passwd, group) } -// parseNumeric parses the given UID or GID value to an integer and within -// the minID - maxID range. +// validateID checks whether a UID or GID is within the supported range, +// returning [ErrRange] if it is not. // -// While the Linux kernel allows the max UID to be MaxUint32 - 2, -// and the OCI Runtime Spec has no definition about the max UID, we require -// the UID to be <= MaxInt32. +// While the Linux kernel allows UIDs up to MaxUint32 - 2, and the OCI +// Runtime Spec does not define a maximum UID, we restrict IDs to MaxInt32 +// for compatibility with 32-bit systems and OCI runtimes. // // See https://github.com/containerd/containerd/commit/de1341c201ffb0effebbf51d00376181968c8779 -func parseNumeric(val string) (int, bool, error) { - if val == "" { - return 0, false, nil +func validateID(id int) error { + if id < minID || id > maxID { + return ErrRange } + return nil +} + +// parseNumeric parses a UID or GID as an integer within the supported range. +func parseNumeric(val string) (int, error) { id, err := strconv.Atoi(val) if err != nil { - if errors.Is(err, strconv.ErrSyntax) { - // Discard the error, because non-numeric values are expected - // when passing a username or group-name. - return 0, false, nil - } if errors.Is(err, strconv.ErrRange) { - return 0, true, ErrRange + return 0, ErrRange } - // Other errors ("invalid base", "invalid bit size"); should never - // happen with strconv.Atoi. - return 0, false, err + return 0, err } - if id < minID || id > maxID { - return 0, true, ErrRange + if err := validateID(id); err != nil { + return 0, err + } + return id, nil +} + +// parseMaybeNumeric parses a UID or GID as a numeric ID, or indicates +// that the value should be interpreted as a username or group name. +// +// Non-numeric values are expected when passing a username or group name, +// so syntax errors are ignored. The boolean indicates whether the value +// was interpreted as a numeric ID. +func parseMaybeNumeric(val string) (int, bool, error) { + id, err := parseNumeric(val) + if errors.Is(err, strconv.ErrSyntax) { + // Discard the error, because non-numeric values are expected + // when passing a username or group-name. + return 0, false, nil } - return id, true, nil + return id, true, err } // GetExecUser parses a user specification string (using the passwd and group @@ -296,51 +341,40 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( user := &ExecUser{ Uid: defaults.Uid, Gid: defaults.Gid, - Sgids: defaults.Sgids, + Sgids: append([]int{}, defaults.Sgids...), // Sgids slice *cannot* be nil. Home: defaults.Home, } - // Sgids slice *cannot* be nil. - if user.Sgids == nil { - user.Sgids = []int{} - } - - // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax - var userArg, groupArg string - parseLine([]byte(userSpec), &userArg, &groupArg) + // Allow for userSpec to have either "user", or optionally "user:group" syntax. + usr, grp, _ := strings.Cut(userSpec, ":") - // Convert userArg and groupArg to be numeric, so we don't have to execute + // Convert usr and grp to be numeric, so we don't have to execute // Atoi *twice* for each iteration over lines. - uidArg, isUID, err := parseNumeric(userArg) + userArg, err := parseUserArg(usr) if err != nil { return nil, err } - gidArg, isGID, err := parseNumeric(groupArg) + groupArg, err := parseGroupArg(grp) if err != nil { return nil, err } // Find the matching user. users, err := ParsePasswdFilter(passwd, func(u User) bool { - if userArg == "" { + if userArg == nil { // Default to current state of the user. return u.Uid == user.Uid } - - if isUID { - // If the userArg is a valid numeric value, always treat it as a UID. - return uidArg == u.Uid - } - - return u.Name == userArg + return userArg.matches(u) }) // If we can't find the user, we have to bail. if err != nil && passwd != nil { - if userArg == "" { - userArg = strconv.Itoa(user.Uid) + name := usr + if userArg == nil { + name = strconv.Itoa(user.Uid) } - return nil, fmt.Errorf("unable to find user %s: %w", userArg, err) + return nil, fmt.Errorf("unable to find user %s: %w", name, err) } var matchedUserName string @@ -350,57 +384,42 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( user.Uid = users[0].Uid user.Gid = users[0].Gid user.Home = users[0].Home - } else if userArg != "" { + } else if userArg != nil { // If we can't find a user with the given username, the only other valid // option is if it's a numeric username with no associated entry in passwd. - - if !isUID { - // Not numeric. - return nil, fmt.Errorf("unable to find user %s: %w", userArg, ErrNoPasswdEntries) + if !userArg.isNumeric { + return nil, fmt.Errorf("unable to find user %s: %w", userArg.name, ErrNoPasswdEntries) } - user.Uid = uidArg + user.Uid = userArg.uid } // On to the groups. If we matched a username, we need to do this because of // the supplementary group IDs. - if groupArg != "" || matchedUserName != "" { + if groupArg != nil || matchedUserName != "" { groups, err := ParseGroupFilter(group, func(g Group) bool { // If the group argument isn't explicit, we'll just search for it. - if groupArg == "" { + if groupArg == nil { // Check if user is a member of this group. - for _, u := range g.List { - if u == matchedUserName { - return true - } - } - return false + return slices.Contains(g.List, matchedUserName) } - - if isGID { - // If the groupArg is numeric, always treat it as a GID. - return gidArg == g.Gid - } - - return g.Name == groupArg + return groupArg.matches(g) }) if err != nil && group != nil { return nil, fmt.Errorf("unable to find groups for spec %v: %w", matchedUserName, err) } // Only start modifying user.Gid if it is in explicit form. - if groupArg != "" { + if groupArg != nil { if len(groups) > 0 { // First match wins, even if there's more than one matching entry. user.Gid = groups[0].Gid } else { // If we can't find a group with the given name, the only other valid // option is if it's a numeric group name with no associated entry in group. - - if !isGID { - // Not numeric. - return nil, fmt.Errorf("unable to find group %s: %w", groupArg, ErrNoGroupEntries) + if !groupArg.isNumeric { + return nil, fmt.Errorf("unable to find group %s: %w", groupArg.name, ErrNoGroupEntries) } - user.Gid = gidArg + user.Gid = groupArg.gid } } else if len(groups) > 0 { // Supplementary group ids only make sense if in the implicit form. @@ -414,39 +433,22 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( return user, nil } -// groupArg is a parsed group argument for [GetAdditionalGroups]. -type groupArg struct { - name string - gid int - isNumeric bool -} - -// matches reports whether group g satisfies the argument. Numeric arguments -// are matched by GID only, others by name. -func (ag groupArg) matches(g Group) bool { - if ag.isNumeric { - return g.Gid == ag.gid - } - return g.Name == ag.name -} - // GetAdditionalGroups looks up a list of groups by name or group id // against the given /etc/group formatted data. If a group name cannot // be found, an error will be returned. If a group id cannot be found, // or the given group data is nil, the id will be returned as-is // provided it is in the legal range. func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { - addtlGroups := make([]groupArg, len(additionalGroups)) - for i, ag := range additionalGroups { - gid, ok, err := parseNumeric(ag) + addtlGroups := make([]groupArg, 0, len(additionalGroups)) + for _, ag := range additionalGroups { + groupArg, err := parseGroupArg(ag) if err != nil { return nil, err } - addtlGroups[i] = groupArg{ - name: ag, - gid: gid, - isNumeric: ok, + if groupArg == nil { + return nil, errors.New("empty group name") } + addtlGroups = append(addtlGroups, *groupArg) } groups := []Group{} @@ -471,9 +473,6 @@ func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, err for _, g := range groups { if ag.matches(g) { // take the first matched group as correct - if g.Gid < minID || g.Gid > maxID { - return nil, ErrRange - } gidMap[g.Gid] = struct{}{} found = true break @@ -501,25 +500,46 @@ func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, err // that opens the groupPath given and gives it as an argument to // GetAdditionalGroups. func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { - var group io.Reader - - if groupFile, err := os.Open(groupPath); err == nil { - group = groupFile - defer groupFile.Close() + groupFile, err := openUserFile(groupPath) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return GetAdditionalGroups(additionalGroups, nil) } - return GetAdditionalGroups(additionalGroups, group) + defer func() { _ = groupFile.Close() }() + + return GetAdditionalGroups(additionalGroups, groupFile) } +// maxSubID is the maximum subordinate ID (maxof(id_t) in shadow-utils). +const maxSubID = 1<<32 - 1 + +// valid reports whether s is a valid subordinate ID range. It follows the +// checks done by shadow-utils: the name must not be empty, and the range +// must fit into 32-bit IDs. +// +// See https://github.com/shadow-maint/shadow/blob/24bc15eac4dcdec9c73c59988fe030b44a98c3de/lib/subordinateio.c#L93-L127 +func (s SubID) valid() bool { + return s.Name != "" && + s.SubID >= 0 && s.SubID <= maxSubID && + s.Count >= 0 && s.Count <= min(maxSubID+1-s.SubID, maxSubID) +} + +// ParseSubIDFile parses subordinate UID/GID ranges from the specified file. func ParseSubIDFile(path string) ([]SubID, error) { return ParseSubIDFileFilter(path, nil) } +// ParseSubID parses subordinate UID/GID ranges from the provided reader. func ParseSubID(subid io.Reader) ([]SubID, error) { return ParseSubIDFilter(subid, nil) } +// ParseSubIDFileFilter parses subordinate UID/GID ranges from the specified +// file, returning only entries matching filter. A nil filter matches all entries. func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) { - subid, err := os.Open(path) + subid, err := openUserFile(path) if err != nil { return nil, err } @@ -527,6 +547,8 @@ func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) return ParseSubIDFilter(subid, filter) } +// ParseSubIDFilter parses subordinate UID/GID ranges from the provided reader, +// returning only entries matching filter. A nil filter matches all entries. func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { if r == nil { return nil, errors.New("nil source for subid-formatted data") @@ -544,8 +566,15 @@ func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { } // see: man 5 subuid + // name:subid:count + // Name:SubID:Count + // user:100000:65536 + parts := bytes.Split(line, []byte(":")) p := SubID{} - parseLine(line, &p.Name, &p.SubID, &p.Count) + if len(parts) != 3 || !parseParts(parts, &p.Name, &p.SubID, &p.Count) || !p.valid() { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) @@ -558,23 +587,36 @@ func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) { return out, nil } +// ParseIDMapFile parses ID mappings from the specified file. func ParseIDMapFile(path string) ([]IDMap, error) { return ParseIDMapFileFilter(path, nil) } +// ParseIDMap parses ID mappings from r. func ParseIDMap(r io.Reader) ([]IDMap, error) { return ParseIDMapFilter(r, nil) } +// ParseIDMapFileFilter parses ID mappings from the specified file, +// returning only entries matching filter. A nil filter matches all entries. +// Reads are limited to 10 MiB, but non-regular files are allowed to support +// procfs-backed UID/GID mapping files. func ParseIDMapFileFilter(path string, filter func(IDMap) bool) ([]IDMap, error) { - r, err := os.Open(path) + // ID mapping files are typically procfs files, so we cannot use + // openUserFile's regular-file check. Enforce the read limit separately. + f, err := os.Open(path) if err != nil { return nil, err } - defer r.Close() + + r := newLimitedFile(f) + defer func() { _ = r.Close() }() + return ParseIDMapFilter(r, filter) } +// ParseIDMapFilter parses ID mappings from r, returning only entries +// matching filter. A nil filter matches all entries. func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) { if r == nil { return nil, errors.New("nil source for idmap-formatted data") @@ -593,7 +635,10 @@ func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) { // see: man 7 user_namespaces p := IDMap{} - parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count) + if !parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count) { + // Skip malformed lines. + continue + } if filter == nil || filter(p) { out = append(out, p) diff --git a/vendor/github.com/moby/sys/user/user_utils.go b/vendor/github.com/moby/sys/user/user_utils.go index 978aa927ed30..86fe8830548e 100644 --- a/vendor/github.com/moby/sys/user/user_utils.go +++ b/vendor/github.com/moby/sys/user/user_utils.go @@ -12,6 +12,8 @@ import ( // generous headroom while bounding memory usage. const maxUserFileBytes = 10 << 20 +var errNotRegularFile = errors.New("not a regular file") + // openUserFile attempts to open a user-database file with a limitedFile // capped at maxUserFileBytes. It produces an error if the given path is // a non-regular file. @@ -31,18 +33,22 @@ func openUserFile(path string) (*limitedFile, error) { return nil, &os.PathError{ Op: "open", Path: path, - Err: errors.New("not a regular file"), + Err: errNotRegularFile, } } + return newLimitedFile(f), nil +} + +func newLimitedFile(f *os.File) *limitedFile { return &limitedFile{ File: f, // Allow one byte past the cap so an overflow surfaces as an // error rather than a silent EOF that the parser would treat as // a clean end-of-file (and miss any entries past the cap). LimitedReader: &io.LimitedReader{R: f, N: maxUserFileBytes + 1}, - name: path, - }, nil + name: f.Name(), + } } type limitedFile struct { @@ -62,3 +68,65 @@ func (l *limitedFile) Read(p []byte) (int, error) { } return n, err } + +// userArg is a parsed user argument for [GetExecUser]. +type userArg struct { + name string + uid int + isNumeric bool +} + +// parseUserArg parses a user argument as either a user name or UID. +// +// If name is empty, parseUserArg returns "nil, nil" to indicate that no user +// argument was specified. +func parseUserArg(name string) (*userArg, error) { + if name == "" { + return nil, nil + } + uid, isNumeric, err := parseMaybeNumeric(name) + if err != nil { + return nil, err + } + return &userArg{name: name, uid: uid, isNumeric: isNumeric}, nil +} + +// matches reports whether user u satisfies the argument. Numeric arguments +// are matched by UID only, others by name. +func (ua *userArg) matches(u User) bool { + if ua.isNumeric { + return u.Uid == ua.uid + } + return u.Name == ua.name +} + +// groupArg is a parsed group argument for [GetAdditionalGroups] or [GetExecUser]. +type groupArg struct { + name string + gid int + isNumeric bool +} + +// parseGroupArg parses a group argument as either a group name or GID. +// +// If name is empty, parseGroupArg returns "nil, nil" to indicate that no group +// argument was specified. +func parseGroupArg(name string) (*groupArg, error) { + if name == "" { + return nil, nil + } + gid, isNumeric, err := parseMaybeNumeric(name) + if err != nil { + return nil, err + } + return &groupArg{name: name, gid: gid, isNumeric: isNumeric}, nil +} + +// matches reports whether group g satisfies the argument. Numeric arguments +// are matched by GID only, others by name. +func (ag groupArg) matches(g Group) bool { + if ag.isNumeric { + return g.Gid == ag.gid + } + return g.Name == ag.name +} diff --git a/vendor/modules.txt b/vendor/modules.txt index a4d5bcda8909..d1d2f7a9a131 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -228,8 +228,8 @@ github.com/moby/sys/signal # github.com/moby/sys/symlink v0.3.0 ## explicit; go 1.17 github.com/moby/sys/symlink -# github.com/moby/sys/user v0.4.1 -## explicit; go 1.18 +# github.com/moby/sys/user v0.5.1 +## explicit; go 1.24 github.com/moby/sys/user # github.com/moby/sys/userns v0.2.1 ## explicit; go 1.21