返回 last30days-skill
cache_security_unix.go
根目录 / mcp / internal / engine / cache_security_unix.go
1 //go:build darwin || dragonfly || freebsd || illumos || linux || netbsd || openbsd
2
3 package engine
4
5 import (
6 "fmt"
7 "os"
8 "path/filepath"
9 "syscall"
10 )
11
12 func cacheParentDir(baseDir string) string {
13 return filepath.Join(filepath.Clean(baseDir), fmt.Sprintf("%s-%d", cacheSubdir, os.Geteuid()))
14 }
15
16 func mkdirPrivate(path string) error {
17 return os.Mkdir(path, 0o700)
18 }
19
20 func ensurePrivateParentDir(parent string) error {
21 if err := os.MkdirAll(parent, 0o700); err != nil {
22 return err
23 }
24 return verifyPrivateDir(parent)
25 }
26
27 func verifyPrivateDir(path string) error {
28 info, err := os.Lstat(path)
29 if err != nil {
30 return err
31 }
32 if info.Mode()&os.ModeSymlink != 0 {
33 return fmt.Errorf("engine: refusing symlink cache directory %s", path)
34 }
35 if !info.IsDir() {
36 return fmt.Errorf("engine: cache path %s is not a directory", path)
37 }
38 st, ok := info.Sys().(*syscall.Stat_t)
39 if !ok {
40 return fmt.Errorf("engine: unable to verify owner of %s", path)
41 }
42 if st.Uid != uint32(os.Geteuid()) {
43 return fmt.Errorf("engine: cache directory %s is not owned by current user", path)
44 }
45 if info.Mode().Perm()&0o022 != 0 {
46 return fmt.Errorf("engine: cache directory %s is writable by group or others (mode %04o)", path, info.Mode().Perm())
47 }
48 return nil
49 }
50
51 func verifyOwnedRegularFile(info os.FileInfo, path string) error {
52 if !info.Mode().IsRegular() {
53 return fmt.Errorf("engine: refusing non-regular cache file %s", path)
54 }
55 st, ok := info.Sys().(*syscall.Stat_t)
56 if !ok {
57 return fmt.Errorf("engine: unable to verify owner of %s", path)
58 }
59 if st.Uid != uint32(os.Geteuid()) {
60 return fmt.Errorf("engine: cache file %s is not owned by current user", path)
61 }
62 return nil
63 }
64
65 func openNoFollowFile(path string, flag int, perm os.FileMode) (*os.File, error) {
66 openFlags := flag | syscall.O_NOFOLLOW
67 if flag&(os.O_WRONLY|os.O_RDWR) == 0 {
68 openFlags |= syscall.O_NONBLOCK
69 }
70 file, err := os.OpenFile(path, openFlags, perm)
71 if err != nil {
72 return nil, err
73 }
74 info, err := file.Stat()
75 if err != nil {
76 _ = file.Close()
77 return nil, err
78 }
79 if err := verifyOwnedRegularFile(info, path); err != nil {
80 _ = file.Close()
81 return nil, err
82 }
83 return file, nil
84 }
85
86 func openRootRegularNoFollow(root *os.Root, cacheDir, nativeRel string) (*os.File, error) {
87 file, err := root.OpenFile(nativeRel, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
88 if err != nil {
89 return nil, err
90 }
91 info, err := file.Stat()
92 if err != nil {
93 _ = file.Close()
94 return nil, err
95 }
96 if err := verifyOwnedRegularFile(info, filepath.Join(cacheDir, nativeRel)); err != nil {
97 _ = file.Close()
98 return nil, err
99 }
100 return file, nil
101 }
102
102 lines GO