| 1 | //go:build linux && !nonamespacing |
| 2 | |
| 3 | package maincmd |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "syscall" |
| 8 | |
| 9 | "github.com/gokrazy/rsync/internal/rsyncos" |
| 10 | ) |
| 11 | |
| 12 | func dropPrivileges(osenv *rsyncos.Env) error { |
| 13 | if syscall.Getuid() != 0 { |
| 14 | return nil |
| 15 | } |
| 16 | |
| 17 | osenv.Logf("running as root (uid 0), dropping privileges to nobody (uid/gid 65534)") |
| 18 | if err := syscall.Setgid(65534); err != nil { |
| 19 | return fmt.Errorf("setgid(65534): %v", err) |
| 20 | } |
| 21 | |
| 22 | if err := syscall.Setuid(65534); err != nil { |
| 23 | return fmt.Errorf("setuid(65534): %v", err) |
| 24 | } |
| 25 | |
| 26 | // Defense in depth: exit if we can re-gain uid/gid 0 permission: |
| 27 | if err := syscall.Setgid(0); err == nil { |
| 28 | //lint:ignore ST1005 we need this punctuation for dramatic effect! |
| 29 | return fmt.Errorf("unexpectedly able to re-gain gid 0 permission!") |
| 30 | } |
| 31 | |
| 32 | if err := syscall.Setuid(0); err == nil { |
| 33 | //lint:ignore ST1005 we need this punctuation for dramatic effect! |
| 34 | return fmt.Errorf("unexpectedly able to re-gain uid 0 permission!") |
| 35 | } |
| 36 | |
| 37 | return nil |
| 38 | } |