返回 DeepSeek-Reasonix
marker.go
根目录 / internal / winaclresidue / marker.go
1 package winaclresidue
2
3 import (
4 "bufio"
5 "os"
6 "path/filepath"
7 "strconv"
8 "strings"
9 )
10
11 type residueKind string
12
13 const (
14 residueDeny residueKind = "deny"
15 residueGrant residueKind = "grant"
16 )
17
18 type residueEntry struct {
19 kind residueKind
20 path string
21 }
22
23 // markerOwnerPID extracts the owning PID from a "<pid>[-nonce].txt" name.
24 func markerOwnerPID(name string) (string, bool) {
25 if !strings.HasSuffix(name, ".txt") {
26 return "", false
27 }
28 pid, _, _ := strings.Cut(strings.TrimSuffix(name, ".txt"), "-")
29 if pid == "" {
30 return "", false
31 }
32 if _, err := strconv.ParseUint(pid, 10, 32); err != nil {
33 return "", false
34 }
35 return pid, true
36 }
37
38 // readResidueMarker parses "<kind>\t<path>" lines. A tab separates the fields
39 // so paths with spaces survive; unrecognized lines are skipped rather than
40 // guessed at, so a corrupt marker cannot cause a wrong ACE removal.
41 func readResidueMarker(path string) []residueEntry {
42 f, err := os.Open(path)
43 if err != nil {
44 return nil
45 }
46 defer f.Close()
47 var out []residueEntry
48 scanner := bufio.NewScanner(f)
49 for scanner.Scan() {
50 kindStr, p, ok := strings.Cut(strings.TrimRight(scanner.Text(), "\r\n"), "\t")
51 if !ok || p == "" {
52 continue
53 }
54 switch kind := residueKind(kindStr); kind {
55 case residueDeny, residueGrant:
56 out = append(out, residueEntry{kind: kind, path: p})
57 }
58 }
59 return out
60 }
61
62 // isWindowsSystemRoot reports whether path lies under a shared system
63 // directory. Markers are untrusted input under %TEMP%; stripping the built-in
64 // package SIDs from System32 or Program Files would remove factory ACEs.
65 // Paths are compared with backslash separators so the rule is the same on
66 // every host that inspects a Windows marker.
67 func isWindowsSystemRoot(path string) bool {
68 clean := windowsPathKey(path)
69 for _, envVar := range []string{"SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"} {
70 root := os.Getenv(envVar)
71 if root == "" {
72 continue
73 }
74 root = windowsPathKey(root)
75 if clean == root || strings.HasPrefix(clean, root+`\`) {
76 return true
77 }
78 }
79 return false
80 }
81
82 func windowsPathKey(path string) string {
83 return strings.ToLower(strings.TrimRight(strings.ReplaceAll(filepath.Clean(path), "/", `\`), `\`))
84 }
85
86 func dedupeSIDStrings(sids []string) []string {
87 out := make([]string, 0, len(sids))
88 seen := map[string]bool{}
89 for _, sid := range sids {
90 if sid == "" || seen[sid] {
91 continue
92 }
93 seen[sid] = true
94 out = append(out, sid)
95 }
96 return out
97 }
98
98 lines GO