| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293 |
- package grpcserver
- import (
- "fmt"
- "net"
- "os"
- "os/user"
- "path/filepath"
- "strconv"
- "strings"
- "syscall"
- "time"
- "hth/internal/config"
- )
- const (
- observeDirMode os.FileMode = 0o2750
- controlDirMode os.FileMode = 0o2750
- runtimeDirMode os.FileMode = 0o0751
- )
- var mkdirComponentImpl func(path string, mode os.FileMode, gid int) error
- // protectedExact must never be chmod/chown/removed by hthd.
- var protectedExact = map[string]struct{}{
- "/": {}, "/tmp": {}, "/run": {}, "/var": {}, "/var/run": {}, "/dev": {}, "/etc": {},
- }
- func isProtectedExact(path string) bool {
- clean, err := filepath.Abs(filepath.Clean(path))
- if err != nil {
- return true
- }
- _, ok := protectedExact[clean]
- return ok
- }
- func underManaged(root, path string) error {
- rootAbs, err := filepath.Abs(filepath.Clean(root))
- if err != nil {
- return err
- }
- pathAbs, err := filepath.Abs(filepath.Clean(path))
- if err != nil {
- return err
- }
- if isProtectedExact(rootAbs) {
- return fmt.Errorf("runtime root %s is a protected parent directory", rootAbs)
- }
- rel, err := filepath.Rel(rootAbs, pathAbs)
- if err != nil {
- return err
- }
- if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
- return fmt.Errorf("path %s is outside runtime root %s", pathAbs, rootAbs)
- }
- return nil
- }
- func lookupGID(group string) (int, error) {
- if group == "" {
- return -1, nil
- }
- g, err := user.LookupGroup(group)
- if err != nil {
- return 0, fmt.Errorf("lookup group %q: %w", group, err)
- }
- gid, err := strconv.Atoi(g.Gid)
- if err != nil {
- return 0, fmt.Errorf("group %q gid: %w", group, err)
- }
- return gid, nil
- }
- func chownPath(path string, gid int) error {
- if gid < 0 {
- return nil
- }
- if err := os.Chown(path, os.Getuid(), gid); err != nil {
- return fmt.Errorf("chown %s: %w", path, err)
- }
- return nil
- }
- func chmodPath(path string, mode os.FileMode) error {
- if isProtectedExact(path) {
- return fmt.Errorf("refusing chmod of protected path %s", path)
- }
- if err := os.Chmod(path, mode); err != nil {
- return fmt.Errorf("chmod %s: %w", path, err)
- }
- return nil
- }
- func applyDirMode(path string, mode os.FileMode, gid int, created bool) error {
- if !created {
- st, err := os.Lstat(path)
- if err != nil {
- return err
- }
- if sys, ok := st.Sys().(*syscall.Stat_t); ok && int(sys.Uid) != os.Geteuid() {
- // Directory belongs to systemd/tmpfiles (e.g. /run/hth root:root).
- // Do not chmod or chown public parents.
- return nil
- }
- }
- if err := chmodPath(path, mode); err != nil {
- return err
- }
- return chownPath(path, gid)
- }
- func mkdirComponent(path string, mode os.FileMode, gid int) error {
- if impl := mkdirComponentImpl; impl != nil {
- return impl(path, mode, gid)
- }
- return mkdirComponentPortable(path, mode, gid)
- }
- func mkdirComponentPortable(path string, mode os.FileMode, gid int) error {
- if isProtectedExact(path) {
- return fmt.Errorf("refusing to create/modify protected path %s", path)
- }
- st, err := os.Lstat(path)
- if err != nil {
- if !os.IsNotExist(err) {
- return err
- }
- if err := os.Mkdir(path, mode); err != nil {
- return fmt.Errorf("mkdir %s: %w", path, err)
- }
- return applyDirMode(path, mode, gid, true)
- }
- if st.Mode()&os.ModeSymlink != 0 {
- target, err := filepath.EvalSymlinks(path)
- if err != nil {
- return fmt.Errorf("symlink %s: %w", path, err)
- }
- if isProtectedExact(target) {
- return fmt.Errorf("symlink %s points at protected path %s", path, target)
- }
- return fmt.Errorf("refusing to enter symlink component %s -> %s", path, target)
- }
- if !st.IsDir() {
- return fmt.Errorf("%s exists and is not a directory", path)
- }
- return applyDirMode(path, mode, gid, false)
- }
- func ensureDirTree(root, dir string, leafMode os.FileMode, gid int) error {
- rootAbs, err := filepath.Abs(filepath.Clean(root))
- if err != nil {
- return err
- }
- dirAbs, err := filepath.Abs(filepath.Clean(dir))
- if err != nil {
- return err
- }
- if err := underManaged(rootAbs, dirAbs); err != nil {
- return err
- }
- if err := mkdirComponent(rootAbs, runtimeDirMode, -1); err != nil {
- return err
- }
- rel, err := filepath.Rel(rootAbs, dirAbs)
- if err != nil {
- return err
- }
- cur := rootAbs
- if rel == "." {
- return chmodPath(dirAbs, leafMode)
- }
- parts := strings.Split(rel, string(os.PathSeparator))
- for i, part := range parts {
- if part == "" || part == "." {
- continue
- }
- cur = filepath.Join(cur, part)
- mode := runtimeDirMode
- g := -1
- if i == len(parts)-1 {
- mode = leafMode
- g = gid
- }
- if err := mkdirComponent(cur, mode, g); err != nil {
- return err
- }
- }
- return nil
- }
- func removeStaleSocket(root, path string) error {
- if err := underManaged(root, path); err != nil {
- return err
- }
- st, err := os.Lstat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- mode := st.Mode()
- switch {
- case mode&os.ModeSymlink != 0:
- return fmt.Errorf("refusing to remove symlink %s", path)
- case mode&os.ModeNamedPipe != 0:
- return fmt.Errorf("refusing to remove FIFO %s", path)
- case mode&os.ModeDevice != 0:
- return fmt.Errorf("refusing to remove device node %s", path)
- case st.IsDir():
- return fmt.Errorf("refusing to remove directory %s", path)
- case mode&os.ModeSocket != 0:
- conn, dialErr := net.DialTimeout("unix", path, 50*time.Millisecond)
- if dialErr == nil {
- _ = conn.Close()
- return fmt.Errorf("unix socket %s is in use; refusing to preempt", path)
- }
- if err := os.Remove(path); err != nil {
- return fmt.Errorf("remove stale socket %s: %w", path, err)
- }
- return nil
- default:
- return fmt.Errorf("refusing to remove non-socket file %s mode %v", path, mode)
- }
- }
- func prepareSocketPath(root, path, group string, dirMode os.FileMode) error {
- if path == "" {
- return fmt.Errorf("socket path required")
- }
- if root == "" {
- return fmt.Errorf("runtime root required")
- }
- if err := underManaged(root, path); err != nil {
- return err
- }
- gid, err := lookupGID(group)
- if err != nil {
- return err
- }
- dir := filepath.Dir(path)
- if err := ensureDirTree(root, dir, dirMode, gid); err != nil {
- return err
- }
- return removeStaleSocket(root, path)
- }
- func chownSocket(path, group string) error {
- gid, err := lookupGID(group)
- if err != nil {
- return err
- }
- if gid < 0 {
- return nil
- }
- st, err := os.Lstat(path)
- if err != nil {
- return err
- }
- if st.Mode()&os.ModeSocket == 0 {
- return fmt.Errorf("chown: %s is not a unix socket", path)
- }
- return chownPath(path, gid)
- }
- func PrepareSocketsForTest(cfg *config.Config) error {
- return prepareSockets(cfg)
- }
- func prepareSockets(cfg *config.Config) error {
- root, err := cfg.ManagedRuntimeRoot()
- if err != nil {
- return err
- }
- if err := prepareSocketPath(root, cfg.Sockets.Observe, cfg.Sockets.ObserveGroup, observeDirMode); err != nil {
- return fmt.Errorf("observe dir: %w", err)
- }
- if err := prepareSocketPath(root, cfg.Sockets.Control, cfg.Sockets.ControlGroup, controlDirMode); err != nil {
- return fmt.Errorf("control dir: %w", err)
- }
- return nil
- }
- // StatMode is used by tests.
- func StatMode(path string) (os.FileMode, error) {
- st, err := os.Lstat(path)
- if err != nil {
- return 0, err
- }
- return st.Mode(), nil
- }
|