Debian Codegraph @

dropprivs_unix.go

raw
1 // Copyright Martin Dosch.
2 // Use of this source code is governed by the BSD-2-clause
3 // license that can be found in the LICENSE file.
4 //go:build !windows
5
6 package main
7
8 import (
9 "fmt"
10 "log/slog"
11 osUser "os/user"
12 "strconv"
13 "syscall"
14 )
15
16 func dropPrivs() error {
17 slog.Info("Trying to drop root privileges before connecting to the server")
18 nobody, err := osUser.Lookup("nobody")
19 if err != nil {
20 slog.Info("failed to look up user nobody, will not drop privileges")
21 return fmt.Errorf("failed to drop root privilege: %w", err)
22 } else {
23 gid, err := strconv.Atoi(nobody.Gid)
24 if err != nil {
25 return fmt.Errorf("failed to drop root privilege: %w", err)
26 }
27 uid, err := strconv.Atoi(nobody.Uid)
28 if err != nil {
29 return fmt.Errorf("failed to drop root privilege: %w", err)
30 }
31 err = syscall.Setgid(gid)
32 if err != nil {
33 slog.Info("failed to drop privileges to user nobody", "GID", gid)
34 return fmt.Errorf("failed to drop root privilege: %w", err)
35 }
36 err = syscall.Setuid(uid)
37 if err != nil {
38 slog.Info("failed to drop privileges to user nobody", "UID", uid)
39 return fmt.Errorf("failed to drop root privilege: %w", err)
40 }
41 }
42 slog.Info("user identification", "UID", syscall.Getuid())
43 slog.Info("user identification", "GID", syscall.Getgid())
44 return nil
45 }