Debian Codegraph @

internal/maincmd/namespacing.go

raw symbols SCIP
1 //go:build !linux || nonamespacing
2
3 package maincmd
4
5 import (
6 "errors"
7 "fmt"
8 "net"
9 "os"
10 "os/exec"
11 "strconv"
12
13 "github.com/gokrazy/rsync/internal/rsyncos"
14 "github.com/gokrazy/rsync/rsyncd"
15 )
16
17 func namespace(osenv *rsyncos.Env, modules []rsyncd.Module, listen string) error {
18 if os.Getenv("GOKRAZY_RSYNC_PRIVDROP") != "" {
19 osenv.Logf("pid %d (privileges dropped)", os.Getpid())
20
21 // Expected by the go-systemd package, and hard to set before creating
22 // the process in Go.
23 os.Setenv("LISTEN_PID", strconv.Itoa(os.Getpid()))
24
25 return nil
26 }
27
28 if os.Getuid() != 0 {
29 version(osenv)
30 osenv.Logf("environment: unprivileged")
31 return nil
32 }
33
34 version(osenv)
35 osenv.Logf("environment: privileged")
36 osenv.Logf("running as root (uid 0), dropping privileges to nobody (uid/gid 65534)")
37
38 exe, err := os.Executable()
39 if err != nil {
40 return err
41 }
42
43 // Create the listener while still running as uid 0 and inherit it, so that
44 // we can listen on port 873 (rsync), which requires CAP_NET_BIND_SERVICE.
45 ln, err := net.Listen("tcp", listen)
46 if err != nil {
47 return err
48 }
49
50 cmd := exec.Command(exe, os.Args[1:]...)
51 cmd.Dir = "/"
52 // TODO: clean the environment
53 cmd.Env = append(os.Environ(),
54 "GOKRAZY_RSYNC_PRIVDROP=1",
55 "LISTEN_FDS=1", // ExtraFiles start at 3
56 "PATH=/bin:"+os.Getenv("PATH"))
57 cmd.Stdin = os.Stdin // for interactive debugging
58 cmd.Stdout = os.Stdout
59 cmd.Stderr = os.Stderr
60 lnFile, err := ln.(*net.TCPListener).File()
61 if err != nil {
62 return err
63 }
64 cmd.ExtraFiles = []*os.File{lnFile}
65 runAsUnprivilegedUser(cmd)
66 if err := cmd.Run(); err != nil {
67 return fmt.Errorf("%v: %v", cmd.Args, err)
68 }
69 return errIsParent
70 }
71
72 var errIsParent = errors.New("re-exec parent process sentinel error")