unixperm.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package grpcserver
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "os/user"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "hth/internal/config"
  13. )
  14. const (
  15. observeDirMode os.FileMode = 0o2750
  16. controlDirMode os.FileMode = 0o2750
  17. runtimeDirMode os.FileMode = 0o0751
  18. )
  19. var mkdirComponentImpl func(path string, mode os.FileMode, gid int) error
  20. // protectedExact must never be chmod/chown/removed by hthd.
  21. var protectedExact = map[string]struct{}{
  22. "/": {}, "/tmp": {}, "/run": {}, "/var": {}, "/var/run": {}, "/dev": {}, "/etc": {},
  23. }
  24. func isProtectedExact(path string) bool {
  25. clean, err := filepath.Abs(filepath.Clean(path))
  26. if err != nil {
  27. return true
  28. }
  29. _, ok := protectedExact[clean]
  30. return ok
  31. }
  32. func underManaged(root, path string) error {
  33. rootAbs, err := filepath.Abs(filepath.Clean(root))
  34. if err != nil {
  35. return err
  36. }
  37. pathAbs, err := filepath.Abs(filepath.Clean(path))
  38. if err != nil {
  39. return err
  40. }
  41. if isProtectedExact(rootAbs) {
  42. return fmt.Errorf("runtime root %s is a protected parent directory", rootAbs)
  43. }
  44. rel, err := filepath.Rel(rootAbs, pathAbs)
  45. if err != nil {
  46. return err
  47. }
  48. if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
  49. return fmt.Errorf("path %s is outside runtime root %s", pathAbs, rootAbs)
  50. }
  51. return nil
  52. }
  53. func lookupGID(group string) (int, error) {
  54. if group == "" {
  55. return -1, nil
  56. }
  57. g, err := user.LookupGroup(group)
  58. if err != nil {
  59. return 0, fmt.Errorf("lookup group %q: %w", group, err)
  60. }
  61. gid, err := strconv.Atoi(g.Gid)
  62. if err != nil {
  63. return 0, fmt.Errorf("group %q gid: %w", group, err)
  64. }
  65. return gid, nil
  66. }
  67. func chownPath(path string, gid int) error {
  68. if gid < 0 {
  69. return nil
  70. }
  71. if err := os.Chown(path, os.Getuid(), gid); err != nil {
  72. return fmt.Errorf("chown %s: %w", path, err)
  73. }
  74. return nil
  75. }
  76. func chmodPath(path string, mode os.FileMode) error {
  77. if isProtectedExact(path) {
  78. return fmt.Errorf("refusing chmod of protected path %s", path)
  79. }
  80. if err := os.Chmod(path, mode); err != nil {
  81. return fmt.Errorf("chmod %s: %w", path, err)
  82. }
  83. return nil
  84. }
  85. func applyDirMode(path string, mode os.FileMode, gid int, created bool) error {
  86. if !created {
  87. st, err := os.Lstat(path)
  88. if err != nil {
  89. return err
  90. }
  91. if sys, ok := st.Sys().(*syscall.Stat_t); ok && int(sys.Uid) != os.Geteuid() {
  92. // Directory belongs to systemd/tmpfiles (e.g. /run/hth root:root).
  93. // Do not chmod or chown public parents.
  94. return nil
  95. }
  96. }
  97. if err := chmodPath(path, mode); err != nil {
  98. return err
  99. }
  100. return chownPath(path, gid)
  101. }
  102. func mkdirComponent(path string, mode os.FileMode, gid int) error {
  103. if impl := mkdirComponentImpl; impl != nil {
  104. return impl(path, mode, gid)
  105. }
  106. return mkdirComponentPortable(path, mode, gid)
  107. }
  108. func mkdirComponentPortable(path string, mode os.FileMode, gid int) error {
  109. if isProtectedExact(path) {
  110. return fmt.Errorf("refusing to create/modify protected path %s", path)
  111. }
  112. st, err := os.Lstat(path)
  113. if err != nil {
  114. if !os.IsNotExist(err) {
  115. return err
  116. }
  117. if err := os.Mkdir(path, mode); err != nil {
  118. return fmt.Errorf("mkdir %s: %w", path, err)
  119. }
  120. return applyDirMode(path, mode, gid, true)
  121. }
  122. if st.Mode()&os.ModeSymlink != 0 {
  123. target, err := filepath.EvalSymlinks(path)
  124. if err != nil {
  125. return fmt.Errorf("symlink %s: %w", path, err)
  126. }
  127. if isProtectedExact(target) {
  128. return fmt.Errorf("symlink %s points at protected path %s", path, target)
  129. }
  130. return fmt.Errorf("refusing to enter symlink component %s -> %s", path, target)
  131. }
  132. if !st.IsDir() {
  133. return fmt.Errorf("%s exists and is not a directory", path)
  134. }
  135. return applyDirMode(path, mode, gid, false)
  136. }
  137. func ensureDirTree(root, dir string, leafMode os.FileMode, gid int) error {
  138. rootAbs, err := filepath.Abs(filepath.Clean(root))
  139. if err != nil {
  140. return err
  141. }
  142. dirAbs, err := filepath.Abs(filepath.Clean(dir))
  143. if err != nil {
  144. return err
  145. }
  146. if err := underManaged(rootAbs, dirAbs); err != nil {
  147. return err
  148. }
  149. if err := mkdirComponent(rootAbs, runtimeDirMode, -1); err != nil {
  150. return err
  151. }
  152. rel, err := filepath.Rel(rootAbs, dirAbs)
  153. if err != nil {
  154. return err
  155. }
  156. cur := rootAbs
  157. if rel == "." {
  158. return chmodPath(dirAbs, leafMode)
  159. }
  160. parts := strings.Split(rel, string(os.PathSeparator))
  161. for i, part := range parts {
  162. if part == "" || part == "." {
  163. continue
  164. }
  165. cur = filepath.Join(cur, part)
  166. mode := runtimeDirMode
  167. g := -1
  168. if i == len(parts)-1 {
  169. mode = leafMode
  170. g = gid
  171. }
  172. if err := mkdirComponent(cur, mode, g); err != nil {
  173. return err
  174. }
  175. }
  176. return nil
  177. }
  178. func removeStaleSocket(root, path string) error {
  179. if err := underManaged(root, path); err != nil {
  180. return err
  181. }
  182. st, err := os.Lstat(path)
  183. if err != nil {
  184. if os.IsNotExist(err) {
  185. return nil
  186. }
  187. return err
  188. }
  189. mode := st.Mode()
  190. switch {
  191. case mode&os.ModeSymlink != 0:
  192. return fmt.Errorf("refusing to remove symlink %s", path)
  193. case mode&os.ModeNamedPipe != 0:
  194. return fmt.Errorf("refusing to remove FIFO %s", path)
  195. case mode&os.ModeDevice != 0:
  196. return fmt.Errorf("refusing to remove device node %s", path)
  197. case st.IsDir():
  198. return fmt.Errorf("refusing to remove directory %s", path)
  199. case mode&os.ModeSocket != 0:
  200. conn, dialErr := net.DialTimeout("unix", path, 50*time.Millisecond)
  201. if dialErr == nil {
  202. _ = conn.Close()
  203. return fmt.Errorf("unix socket %s is in use; refusing to preempt", path)
  204. }
  205. if err := os.Remove(path); err != nil {
  206. return fmt.Errorf("remove stale socket %s: %w", path, err)
  207. }
  208. return nil
  209. default:
  210. return fmt.Errorf("refusing to remove non-socket file %s mode %v", path, mode)
  211. }
  212. }
  213. func prepareSocketPath(root, path, group string, dirMode os.FileMode) error {
  214. if path == "" {
  215. return fmt.Errorf("socket path required")
  216. }
  217. if root == "" {
  218. return fmt.Errorf("runtime root required")
  219. }
  220. if err := underManaged(root, path); err != nil {
  221. return err
  222. }
  223. gid, err := lookupGID(group)
  224. if err != nil {
  225. return err
  226. }
  227. dir := filepath.Dir(path)
  228. if err := ensureDirTree(root, dir, dirMode, gid); err != nil {
  229. return err
  230. }
  231. return removeStaleSocket(root, path)
  232. }
  233. func chownSocket(path, group string) error {
  234. gid, err := lookupGID(group)
  235. if err != nil {
  236. return err
  237. }
  238. if gid < 0 {
  239. return nil
  240. }
  241. st, err := os.Lstat(path)
  242. if err != nil {
  243. return err
  244. }
  245. if st.Mode()&os.ModeSocket == 0 {
  246. return fmt.Errorf("chown: %s is not a unix socket", path)
  247. }
  248. return chownPath(path, gid)
  249. }
  250. func PrepareSocketsForTest(cfg *config.Config) error {
  251. return prepareSockets(cfg)
  252. }
  253. func prepareSockets(cfg *config.Config) error {
  254. root, err := cfg.ManagedRuntimeRoot()
  255. if err != nil {
  256. return err
  257. }
  258. if err := prepareSocketPath(root, cfg.Sockets.Observe, cfg.Sockets.ObserveGroup, observeDirMode); err != nil {
  259. return fmt.Errorf("observe dir: %w", err)
  260. }
  261. if err := prepareSocketPath(root, cfg.Sockets.Control, cfg.Sockets.ControlGroup, controlDirMode); err != nil {
  262. return fmt.Errorf("control dir: %w", err)
  263. }
  264. return nil
  265. }
  266. // StatMode is used by tests.
  267. func StatMode(path string) (os.FileMode, error) {
  268. st, err := os.Lstat(path)
  269. if err != nil {
  270. return 0, err
  271. }
  272. return st.Mode(), nil
  273. }