goipam/utils/dropPrivileges.go

45 lines
618 B
Go
Raw Permalink Normal View History

2024-02-22 10:18:59 +01:00
package utils
import (
"log"
"os/user"
"strconv"
"syscall"
"github.com/spf13/viper"
)
func DropPrivileges() {
currentUser, err := user.Current()
if err != nil {
log.Fatal(err)
}
if currentUser.Uid == "0" {
return
}
targetUser, err := user.Lookup(viper.GetString("user"))
if err != nil {
log.Fatal(err)
}
uid, err := strconv.Atoi(targetUser.Uid)
if err != nil {
log.Fatal(err)
}
gid, err := strconv.Atoi(targetUser.Gid)
if err != nil {
log.Fatal(err)
}
err = syscall.Setuid(uid)
if err != nil {
log.Fatal(err)
}
err = syscall.Setgid(gid)
if err != nil {
log.Fatal(err)
}
}