Skip to content

Commit 2a8ddac

Browse files
committed
Rewrite chuser() for simplicity and correctness
- Use unambiguous variable names (w/o package name conflict). - Fail on invalid input such as the empty string or `:`. - Do not change group without user, i.e. fail on `:group`. - Parse input using mnemonic APIs. - Do not juggle between integer types. - Unset supplementary groups. - Use setres[ug]id(2) to match the idiom of OpenBSD base programs. Includes/Supersedes yggdrasil-network#1202. Fixes yggdrasil-network#927. I only tested on OpenBSD (so far), hence the split, but other systems should just work.
1 parent eef6139 commit 2a8ddac

File tree

2 files changed

+59
-2
lines changed

2 files changed

+59
-2
lines changed

cmd/yggdrasil/chuser_openbsd.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//go:build openbsd
2+
// +build openbsd
3+
4+
package main
5+
6+
import (
7+
"fmt"
8+
"os/user"
9+
"strconv"
10+
"strings"
11+
12+
"golang.org/x/sys/unix"
13+
)
14+
15+
func chuser(input string) error {
16+
givenUser, givenGroup, _ := strings.Cut(input, ":")
17+
18+
var (
19+
err error
20+
usr *user.User
21+
grp *user.Group
22+
uid, gid int
23+
)
24+
25+
if usr, err = user.Lookup(givenUser); err != nil {
26+
if usr, err = user.LookupId(givenUser); err != nil {
27+
return err
28+
}
29+
}
30+
if uid, err = strconv.Atoi(usr.Uid); err != nil {
31+
return err
32+
}
33+
34+
if givenGroup != "" {
35+
if grp, err = user.LookupGroup(givenGroup); err != nil {
36+
if grp, err = user.LookupGroupId(givenGroup); err != nil {
37+
return err
38+
}
39+
}
40+
41+
gid, _ = strconv.Atoi(grp.Gid)
42+
} else {
43+
gid, _ = strconv.Atoi(usr.Gid)
44+
}
45+
46+
if err := unix.Setgroups([]int{gid}); err != nil {
47+
return fmt.Errorf("setgroups: %d: %v", gid, err)
48+
}
49+
if err := unix.Setresgid(gid, gid, gid); err != nil {
50+
return fmt.Errorf("setresgid: %d: %v", gid, err)
51+
}
52+
if err := unix.Setresuid(uid, uid, uid); err != nil {
53+
return fmt.Errorf("setresuid: %d: %v", uid, err)
54+
}
55+
56+
return nil
57+
}

cmd/yggdrasil/chuser_unix.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
2-
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
1+
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || solaris
2+
// +build aix darwin dragonfly freebsd linux netbsd solaris
33

44
package main
55

0 commit comments

Comments
 (0)