diff --git a/util/osuser/group_ids.go b/util/osuser/group_ids.go index 34d15c926..4d43f2dcc 100644 --- a/util/osuser/group_ids.go +++ b/util/osuser/group_ids.go @@ -5,8 +5,8 @@ package osuser import ( "context" + "errors" "fmt" - "os/exec" "os/user" "runtime" "strings" @@ -42,15 +42,20 @@ func GetGroupIds(user *user.User) ([]string, error) { } func getGroupIdsWithId(usernameOrUID string) ([]string, error) { + // Do some basic validation before passing this string to the "id" + // command, with the same rules as getent (see checkGetentInput), so a + // crafted username like "-u" can't be interpreted as an option. + if !checkGetentInput(usernameOrUID) { + return nil, errors.New("invalid username or UID") + } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - cmd := exec.CommandContext(ctx, "id", "-Gz", usernameOrUID) + idArgs := []string{"-Gz", usernameOrUID} if runtime.GOOS == "freebsd" { - cmd = exec.CommandContext(ctx, "id", "-G", usernameOrUID) + idArgs = []string{"-G", usernameOrUID} } - - out, err := cmd.CombinedOutput() + out, err := execId(ctx, idArgs...) if err != nil { return nil, fmt.Errorf("running 'id' command: %w", err) } diff --git a/util/osuser/group_ids_test.go b/util/osuser/group_ids_test.go index fee86029b..07c70df37 100644 --- a/util/osuser/group_ids_test.go +++ b/util/osuser/group_ids_test.go @@ -4,6 +4,7 @@ package osuser import ( + "context" "slices" "testing" ) @@ -26,3 +27,72 @@ func TestParseGroupIds(t *testing.T) { } } } + +func TestGetGroupIdsWithIdValidatesInput(t *testing.T) { + origExecId := execId + t.Cleanup(func() { + execId = origExecId + }) + + tests := []struct { + name string + username string + wantExec bool + wantExecArg string // the username argument passed to "id" + wantErr bool + }{ + { + name: "valid-username", + username: "alice", + wantExec: true, + wantExecArg: "alice", + }, + { + name: "leading-dash", + username: "-u", + wantErr: true, + }, + { + name: "empty", + username: "", + wantErr: true, + }, + { + name: "control-character", + username: "ali\x00ce", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + execId = func(_ context.Context, args ...string) ([]byte, error) { + if !tt.wantExec { + t.Fatalf("exec 'id' called with %q; want it not to be called", args) + } + wantArg := tt.wantExecArg + gotFlag := args[0] + if gotFlag != "-Gz" && gotFlag != "-G" { + t.Errorf("unexpected 'id' flag %q", gotFlag) + } + if got := args[len(args)-1]; got != wantArg { + t.Errorf("id called with %q; want username %q", got, wantArg) + } + return []byte("1000\x001001\x00"), nil + } + ids, err := getGroupIdsWithId(tt.username) + if tt.wantErr { + if err == nil { + t.Fatalf("getGroupIdsWithId(%q) = %v; want error", tt.username, ids) + } + return + } + if err != nil { + t.Fatalf("getGroupIdsWithId(%q) error: %v", tt.username, err) + } + if !slices.Equal(ids, []string{"1000", "1001"}) { + t.Errorf("ids = %v; want [1000 1001]", ids) + } + }) + } +} diff --git a/util/osuser/user.go b/util/osuser/user.go index 3fdbfbbd3..5a9e26ff1 100644 --- a/util/osuser/user.go +++ b/util/osuser/user.go @@ -57,6 +57,10 @@ var execGetent = func(ctx context.Context, args ...string) ([]byte, error) { return exec.CommandContext(ctx, "getent", args...).Output() } +var execId = func(ctx context.Context, args ...string) ([]byte, error) { + return exec.CommandContext(ctx, "id", args...).CombinedOutput() +} + var getentDoubleDashSupported = sync.OnceValue(probeGetentDoubleDashSupport) func lookup(usernameOrUID string, std lookupStd, wantShell bool) (*user.User, string, error) { @@ -217,7 +221,21 @@ func probeGetentDoubleDashSupport() bool { func parseGetentUser(out []byte) (*user.User, string, error) { // output is "alice:x:1001:1001:Alice Smith,,,:/home/alice:/bin/bash" - f := strings.SplitN(strings.TrimSpace(string(out)), ":", 10) + // + // A single getent record is one line; embedded newlines mean getent + // returned multiple or corrupted records. A record is exactly seven + // colon-separated fields — the passwd format has no escaping (gecos + // sub-fields are comma-separated), so an eighth field means a stray + // colon shifted every later field: home would parse as a gecos + // fragment and shell as the real home directory. + s := strings.TrimSpace(string(out)) + if strings.ContainsRune(s, '\n') { + return nil, "", errors.New("getent passwd output is not a single line") + } + f := strings.SplitN(s, ":", 10) + if len(f) > 7 { + return nil, "", fmt.Errorf("getent passwd output has %d fields, want 7", len(f)) + } for len(f) < 7 { f = append(f, "") } @@ -227,6 +245,15 @@ func parseGetentUser(out []byte) (*user.User, string, error) { return nil, "", fmt.Errorf("missing mandatory field %q", v) } } + // The username and shell are used to look up and run a session; reject + // corrupted values (control characters, invalid UTF-8, leading dashes) + // with the same rules as getent input (see checkGetentInput). + if !checkParsedGetentField(f[0]) { + return nil, "", fmt.Errorf("invalid username field %q", f[0]) + } + if !checkParsedGetentField(f[6]) { + return nil, "", fmt.Errorf("invalid shell field %q", f[6]) + } return &user.User{ Username: f[0], Uid: f[2], @@ -235,3 +262,19 @@ func parseGetentUser(out []byte) (*user.User, string, error) { HomeDir: f[5], }, f[6], nil } + +// checkParsedGetentField reports whether a parsed getent passwd field (the +// username or shell) is safe to use: no leading dash and no control or +// invalid-UTF-8 characters. It doesn't require the field to be non-empty; +// mandatory fields are checked by the caller. +func checkParsedGetentField(s string) bool { + if strings.HasPrefix(s, "-") { + return false + } + for _, r := range s { + if r < ' ' || r == 0x7f || r == utf8.RuneError { + return false + } + } + return true +} diff --git a/util/osuser/user_test.go b/util/osuser/user_test.go index cbea237af..d849cc74c 100644 --- a/util/osuser/user_test.go +++ b/util/osuser/user_test.go @@ -101,3 +101,84 @@ func TestUserLookupGetentUsesProbeResult(t *testing.T) { }) } } + +func TestParseGetentUserRejectsCorruptOutput(t *testing.T) { + tests := []struct { + name string + out string + wantErr bool + }{ + { + name: "valid", + out: "alice:x:1001:1001:Alice Smith,,,:/home/alice:/bin/bash\n", + }, + { + name: "missing-shell-field", + // A missing shell is not corruption; the caller falls back to + // the default shell logic. + out: "alice:x:1001:1001:Alice Smith,,,:/home/alice\n", + }, + { + name: "multi-line", + out: "alice:x:1001:1001:Alice:/home/alice:/bin/bash\nbob:x:1002:1002:Bob:/home/bob:/bin/sh\n", + wantErr: true, + }, + { + name: "control-char-in-name", + out: "ali\x00ce:x:1001:1001:Alice:/home/alice:/bin/bash\n", + wantErr: true, + }, + { + name: "newline-in-shell", + out: "alice:x:1001:1001:Alice:/home/alice:/bin/ba\nsh\n", + wantErr: true, + }, + { + name: "leading-dash-name", + out: "-u:x:1001:1001:Alice:/home/alice:/bin/bash\n", + wantErr: true, + }, + { + name: "leading-dash-shell", + out: "alice:x:1001:1001:Alice:/home/alice:-/bin/bash\n", + wantErr: true, + }, + { + name: "invalid-utf8-in-name", + out: "ali\xc3:x:1001:1001:Alice:/home/alice:/bin/bash\n", + wantErr: true, + }, + { + // A colon in gecos (or any field) makes an eighth field; every + // field after it shifts left — home parses as a gecos fragment + // and shell as the real home directory — so reject instead of + // silently mis-parsing. + name: "colon-in-gecos", + out: "alice:x:1001:1001:Alice:Smith:/home/alice:/bin/bash\n", + wantErr: true, + }, + { + name: "eight-fields", + out: "alice:x:1001:1001:Alice:/home/alice:/bin/bash:extra\n", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + u, shell, err := parseGetentUser([]byte(tt.out)) + if tt.wantErr { + if err == nil { + t.Fatalf("parseGetentUser(%q) = %v, %q; want error", tt.out, u, shell) + } + return + } + if err != nil { + t.Fatalf("parseGetentUser(%q) error: %v", tt.out, err) + } + if u.Username != "alice" && tt.name == "valid" { + t.Errorf("Username = %q; want alice", u.Username) + } + }) + } +}