diff --git a/user/lookup_unix.go b/user/lookup_unix.go index 4540747..570793f 100644 --- a/user/lookup_unix.go +++ b/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/user/user.go b/user/user.go index 3d77c54..1f79132 100644 --- a/user/user.go +++ b/user/user.go @@ -129,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 } @@ -500,13 +500,16 @@ 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). @@ -532,7 +535,7 @@ func ParseSubID(subid io.Reader) ([]SubID, error) { } 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 } diff --git a/user/user_test.go b/user/user_test.go index b832dfc..1e9be2c 100644 --- a/user/user_test.go +++ b/user/user_test.go @@ -143,6 +143,128 @@ this is just some garbage data } } +// TestParsePasswdFileCapsReads asserts the boundary behavior of the read cap: +// well below, ending exactly at, and past maxUserFileBytes. +func TestParsePasswdFileCapsReads(t *testing.T) { + beyond := []byte("\nbeyond:x:42:42::/home/beyond:/bin/sh\n") + + for _, tc := range []struct { + name string + padBytes int + expUIDs []int + expErr string + }{ + { + name: "pad below cap, beyond is parsed", + padBytes: 100, + expUIDs: []int{42}, + }, + { + name: "beyond ends exactly at cap, is parsed", + padBytes: maxUserFileBytes - len(beyond), + expUIDs: []int{42}, + }, + { + name: "pad past cap, read errors out", + padBytes: maxUserFileBytes, + expErr: "file exceeds", + }, + } { + t.Run(tc.name, func(t *testing.T) { + tmpDir := t.TempDir() + fileName := filepath.Join(tmpDir, "etc-passwd") + + pattern := []byte("# padding\n") + pad := bytes.Repeat(pattern, (tc.padBytes+len(pattern)-1)/len(pattern))[:tc.padBytes] + if len(pad) > 0 && pad[len(pad)-1] != '\n' { + pad[len(pad)-1] = '\n' + } + + data := append(pad, beyond...) + err := os.WriteFile(fileName, data, 0o644) + if err != nil { + t.Fatal(err) + } + users, err := ParsePasswdFile(fileName) + if tc.expErr != "" { + if err == nil { + t.Fatal("expected error") + } + if !strings.Contains(err.Error(), tc.expErr) { + t.Fatalf("unexpected error: %s", err) + } + return + } + if err != nil { + t.Fatal(err) + } + haveUIDs := make([]int, 0, len(users)) + for _, u := range users { + haveUIDs = append(haveUIDs, u.Uid) + } + if !reflect.DeepEqual(haveUIDs, tc.expUIDs) { + t.Fatalf("unexpected uids: got %v, want %v", haveUIDs, tc.expUIDs) + } + }) + } +} + +// TestParsePasswdFileOpenErrors verifies that non-regular and missing files are rejected. +func TestParsePasswdFileOpenErrors(t *testing.T) { + tmpDir := t.TempDir() + + tests := []struct { + doc string + fileName string + expError error + }{ + { + doc: "directory", + fileName: tmpDir, + expError: errNotRegularFile, + }, + { + doc: "device", + fileName: "/dev/zero", + expError: errNotRegularFile, + }, + { + doc: "not found", + fileName: filepath.Join(tmpDir, "missing"), + expError: os.ErrNotExist, + }, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + if tc.doc == "device" && runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip("depends on /dev/zero") + } + + _, err := ParsePasswdFile(tc.fileName) + if !errors.Is(err, tc.expError) { + t.Fatalf("expected error %v, got %v", tc.expError, err) + } + }) + } +} + +func TestParsePasswdFilterDevZero(t *testing.T) { + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip("depends on /dev/zero") + } + dn, err := os.Open("/dev/zero") + if err != nil { + t.Fatal(err) + } + defer func() { _ = dn.Close() }() + + const expErr = "bufio.Scanner: token too long" + _, err = ParsePasswdFilter(dn, nil) + if err == nil || !strings.Contains(err.Error(), expErr) { + t.Fatalf("want %q, got %v", expErr, err) + } +} + func TestParseGroupFilter(t *testing.T) { groups, err := ParseGroupFilter(strings.NewReader(` root:x:0:root @@ -317,6 +439,8 @@ func TestParseGroupFilterDevZero(t *testing.T) { if err != nil { t.Fatal(err) } + defer func() { _ = dn.Close() }() + const expErr = "bufio.Scanner: token too long" _, err = ParseGroupFilter(dn, nil) if err == nil || !strings.Contains(err.Error(), expErr) { @@ -359,6 +483,103 @@ func TestParseSubIDFilter(t *testing.T) { } } +// TestParseSubIDFileCapsReads asserts the boundary behavior of the read cap: +// well below, ending exactly at, and past maxUserFileBytes. +func TestParseSubIDFileCapsReads(t *testing.T) { + beyond := []byte("\nbeyond:100000:65536\n") + + for _, tc := range []struct { + name string + padBytes int + expSubIDs []SubID + expErr string + }{ + { + name: "pad below cap, beyond is parsed", + padBytes: 100, + expSubIDs: []SubID{{Name: "beyond", SubID: 100000, Count: 65536}}, + }, + { + name: "beyond ends exactly at cap, is parsed", + padBytes: maxUserFileBytes - len(beyond), + expSubIDs: []SubID{{Name: "beyond", SubID: 100000, Count: 65536}}, + }, + { + name: "pad past cap, read errors out", + padBytes: maxUserFileBytes, + expErr: "file exceeds", + }, + } { + t.Run(tc.name, func(t *testing.T) { + tmpDir := t.TempDir() + fileName := filepath.Join(tmpDir, "etc-subuid") + + pad := bytes.Repeat([]byte("\n"), tc.padBytes) + data := append(pad, beyond...) + + if err := os.WriteFile(fileName, data, 0o644); err != nil { + t.Fatal(err) + } + + subids, err := ParseSubIDFile(fileName) + if tc.expErr != "" { + if err == nil { + t.Fatal("expected error") + } + if !strings.Contains(err.Error(), tc.expErr) { + t.Fatalf("unexpected error: %s", err) + } + return + } + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(subids, tc.expSubIDs) { + t.Fatalf("unexpected subids: got %v, want %v", subids, tc.expSubIDs) + } + }) + } +} + +// TestParseSubIDFileOpenErrors verifies that non-regular and missing files are rejected. +func TestParseSubIDFileOpenErrors(t *testing.T) { + tmpDir := t.TempDir() + + tests := []struct { + doc string + fileName string + expError error + }{ + { + doc: "directory", + fileName: tmpDir, + expError: errNotRegularFile, + }, + { + doc: "device", + fileName: "/dev/zero", + expError: errNotRegularFile, + }, + { + doc: "not found", + fileName: filepath.Join(tmpDir, "missing"), + expError: os.ErrNotExist, + }, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + if tc.doc == "device" && runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip("depends on /dev/zero") + } + + _, err := ParseSubIDFile(tc.fileName) + if !errors.Is(err, tc.expError) { + t.Fatalf("expected error %v, got %v", tc.expError, err) + } + }) + } +} + func TestGetExecUser(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash @@ -867,6 +1088,84 @@ func TestGetAdditionalGroupsNumeric(t *testing.T) { } } +func TestGetAdditionalGroupsPathCapsReads(t *testing.T) { + entry := []byte("beyond:x:42:\n") + for _, tc := range []struct { + name string + size int + wantErr bool + }{ + {name: "below cap", size: 100}, + {name: "exactly at cap", size: maxUserFileBytes}, + {name: "past cap", size: maxUserFileBytes + 1, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + fileName := filepath.Join(t.TempDir(), "etc-group") + data := append([]byte(nil), entry...) + data = append(data, bytes.Repeat([]byte("\n"), tc.size-len(entry))...) + if err := os.WriteFile(fileName, data, 0o644); err != nil { + t.Fatal(err) + } + gids, err := GetAdditionalGroupsPath([]string{"beyond"}, fileName) + if tc.wantErr { + if err == nil || !strings.Contains(err.Error(), "file exceeds") { + t.Fatalf("expected file size error, got %v", err) + } + if len(gids) != 0 { + t.Fatalf("unexpected partial results: %v", gids) + } + return + } + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(gids, []int{42}) { + t.Fatalf("unexpected gids: got %v, want [42]", gids) + } + }) + } +} + +// TestGetAdditionalGroupsPathOpenErrors verifies that non-regular and missing +// files are handled correctly. +func TestGetAdditionalGroupsPathOpenErrors(t *testing.T) { + tempDir := t.TempDir() + + tests := []struct { + doc string + fileName string + expError error + }{ + { + doc: "directory", + fileName: tempDir, + expError: errNotRegularFile, + }, + { + doc: "device", + fileName: "/dev/zero", + expError: errNotRegularFile, + }, + { + doc: "not found", + fileName: filepath.Join(tempDir, "missing"), + expError: ErrNoGroupEntries, + }, + } + for _, tc := range tests { + t.Run(tc.doc, func(t *testing.T) { + if tc.doc == "device" && runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip("depends on /dev/zero") + } + + _, err := GetAdditionalGroupsPath([]string{"beyond"}, tc.fileName) + if !errors.Is(err, tc.expError) { + t.Fatalf("expected error %v, got %v", tc.expError, err) + } + }) + } +} + // Generate a proper "largegroup" entry for group tests. func largeGroup() (res string) { var b strings.Builder