oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package creds is a Mac worker's Claude credential guards (Mac runners
2// spec §8.3, §8.7; slice F task 10): the home guard, which decides from
3// ownership, mode bits and ACLs whether anyone else could reach the
4// folders a connection lives in, and the Keychain watch around a
5// sign-in. It reads facts through seams (ls -led and lstat, security
6// dump-keychain), so everything here is tested with recorded outputs.
7package creds
8
9import (
10 "errors"
11 "io/fs"
12 "os"
13 "path/filepath"
14 "regexp"
15 "slices"
16 "strconv"
17 "strings"
18 "syscall"
19
20 "amadan.net/oficina/equipo/internal/runner/mac/proc"
21)
22
23// ACE is one access control entry as ls -le prints it:
24// " 0: user:vicky inherited allow read,write".
25type ACE struct {
26 Index int
27 Who string
28 Inherited bool
29 Allow bool
30 Rights []string
31}
32
33// Fact is what the guard knows of one path: its kind ('d' a directory,
34// 'l' a link, '-' a file), its permission bits, its owner (the name ls
35// prints and the uid lstat reads, -1 unknown) and its ACL entries.
36type Fact struct {
37 Path string
38 Kind byte
39 Perm fs.FileMode
40 Owner string
41 UID int
42 ACL []ACE
43 Missing bool
44}
45
46var (
47 lsHeader = regexp.MustCompile(`^([-dlbcps])([-rwxsStT]{9})([@+]?)\s+\d+\s+(\S+)\s+(\S+)\s+\d+\s+\S+\s+\S+\s+\S+\s+(.+)$`)
48 lsEntry = regexp.MustCompile(`^\s*(\d+): (\S+) (inherited )?(allow|deny) ([a-z_]+(?:,[a-z_]+)*)$`)
49)
50
51// ErrUnreadable: ls output the guard cannot read for sure. It decides
52// nothing from it.
53var ErrUnreadable = errors.New("creds: ls output not understood")
54
55// ParseLS reads `ls -led` output: each path's line and the ACL entries
56// under it. A line it does not understand, or a "+" with no entry, is
57// ErrUnreadable.
58func ParseLS(out string) ([]Fact, error) {
59 var facts []Fact
60 plus := false
61 end := func() error {
62 if len(facts) > 0 && plus && len(facts[len(facts)-1].ACL) == 0 {
63 return ErrUnreadable
64 }
65 return nil
66 }
67 for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") {
68 if line == "" {
69 continue
70 }
71 if m := lsEntry.FindStringSubmatch(line); m != nil {
72 if len(facts) == 0 {
73 return nil, ErrUnreadable
74 }
75 f := &facts[len(facts)-1]
76 n, _ := strconv.Atoi(m[1])
77 if n != len(f.ACL) {
78 return nil, ErrUnreadable
79 }
80 f.ACL = append(f.ACL, ACE{Index: n, Who: m[2], Inherited: m[3] != "", Allow: m[4] == "allow", Rights: strings.Split(m[5], ",")})
81 continue
82 }
83 m := lsHeader.FindStringSubmatch(line)
84 if m == nil {
85 return nil, ErrUnreadable
86 }
87 if err := end(); err != nil {
88 return nil, err
89 }
90 path := m[6]
91 if m[1] == "l" {
92 path, _, _ = strings.Cut(path, " -> ")
93 }
94 facts = append(facts, Fact{Path: path, Kind: m[1][0], Perm: permOf(m[2]), Owner: m[4], UID: -1})
95 plus = m[3] == "+"
96 }
97 if err := end(); err != nil {
98 return nil, err
99 }
100 return facts, nil
101}
102
103// permOf is the 0777 bits of an ls mode string ("rwxr-x---"): s and t
104// carry x, S and T do not.
105func permOf(s string) fs.FileMode {
106 var p fs.FileMode
107 for i, c := range s {
108 if c != '-' && c != 'S' && c != 'T' {
109 p |= 1 << (8 - i)
110 }
111 }
112 return p
113}
114
115// Read is path's fact: the kind, mode and owner lstat reads (never
116// following a link), and, when ls is set, the ACL `ls -led` prints, its
117// mode and owner required to agree. ls nil (off a Mac) reads no ACL.
118func Read(path string, ls func(string) (string, error)) (Fact, error) {
119 info, err := os.Lstat(path)
120 if errors.Is(err, fs.ErrNotExist) {
121 return Fact{Path: path, Missing: true, UID: -1}, nil
122 }
123 if err != nil {
124 return Fact{}, err
125 }
126 f := Fact{Path: path, Kind: '-', Perm: info.Mode().Perm(), UID: -1}
127 switch {
128 case info.Mode()&fs.ModeSymlink != 0:
129 f.Kind = 'l'
130 case info.IsDir():
131 f.Kind = 'd'
132 case !info.Mode().IsRegular():
133 f.Kind = '?'
134 }
135 if st, ok := info.Sys().(*syscall.Stat_t); ok {
136 f.UID = int(st.Uid)
137 }
138 if ls == nil {
139 return f, nil
140 }
141 out, err := ls(path)
142 if err != nil {
143 return Fact{}, err
144 }
145 facts, err := ParseLS(out)
146 if err != nil || len(facts) != 1 || facts[0].Path != path || facts[0].Kind != f.Kind || facts[0].Perm != f.Perm {
147 return Fact{}, ErrUnreadable
148 }
149 f.Owner, f.ACL = facts[0].Owner, facts[0].ACL
150 return f, nil
151}
152
153// Problem codes: what is wrong, in the capability string rules (the
154// Engineering status's reason).
155const (
156 CodeHomeMode = "home_mode"
157 CodeMode = "mode"
158 CodeACL = "acl"
159 CodeOwner = "owner"
160 CodeOutside = "outside"
161 CodeLink = "link"
162 CodeMissing = "missing"
163 CodeUnknown = "unknown"
164)
165
166// Input is what the guard checks: the runner user (name and uid), its
167// home, and the roots that must be private inside it (the state dir,
168// the config dir, the accounts root).
169type Input struct {
170 User string
171 UID int
172 Home string
173 Roots []string
174}
175
176// Problem is one thing to change: the path, the code, and the command
177// that changes it, run as the runner user unless it says otherwise.
178type Problem struct {
179 Path, Code, Fix string
180}
181
182// Result is the guard's verdict: no problem passes.
183type Result struct {
184 Problems []Problem
185}
186
187// OK: nobody else can list, traverse, read or replace any root.
188func (r Result) OK() bool { return len(r.Problems) == 0 }
189
190// Reason is the first problem's code, "" when it passes.
191func (r Result) Reason() string {
192 if r.OK() {
193 return ""
194 }
195 return r.Problems[0].Code
196}
197
198// Fix is every change to make, in order, one per line.
199func (r Result) Fix() string {
200 var out []string
201 for _, p := range r.Problems {
202 if !slices.Contains(out, p.Fix) {
203 out = append(out, p.Fix)
204 }
205 }
206 return strings.Join(out, "\n")
207}
208
209// Check decides from ownership, mode bits and ACLs alone, through read,
210// never by opening anything as this user (which cannot see what another
211// user sees). It passes only when the home and every root are real
212// directories inside the home, owned by the user, with no group or other
213// bit and no ACL entry allowing anyone else anything (inherited or not),
214// and every directory between the home and a root is a real directory
215// the user owns, with no group or other write bit and no such entry.
216func Check(in Input, read func(string) (Fact, error)) Result {
217 var r Result
218 home := filepath.Clean(in.Home)
219 add := func(p, code, fix string) {
220 r.Problems = append(r.Problems, Problem{Path: p, Code: code, Fix: fix})
221 }
222 if !filepath.IsAbs(in.Home) || home == "/" || in.User == "" || in.UID < 0 {
223 add(in.Home, CodeUnknown, "the runner user's home could not be checked")
224 return r
225 }
226 // The protected set first: a root is held to the root rule however
227 // it is reached, as another root's ancestor or as itself. Facts are
228 // read once; each path's problems are said once.
229 protected := map[string]bool{home: true}
230 for _, root := range in.Roots {
231 if p := filepath.Clean(root); filepath.IsAbs(root) && within(home, p) {
232 protected[p] = true
233 }
234 }
235 facts := map[string]Fact{}
236 errs := map[string]error{}
237 usable := map[string]bool{}
238 done := map[string]bool{}
239 look := func(p string) bool {
240 if done[p] {
241 return usable[p]
242 }
243 done[p] = true
244 f, ok := facts[p]
245 if !ok {
246 f, errs[p] = read(p)
247 facts[p] = f
248 }
249 root, at := protected[p], tilde(home, p)
250 switch {
251 case errs[p] != nil:
252 add(p, CodeUnknown, at+" could not be checked")
253 return false
254 case f.Missing:
255 add(p, CodeMissing, "mkdir -m 700 "+at)
256 return false
257 case f.Kind == 'l':
258 add(p, CodeLink, "replace the link "+at+" with a folder")
259 return false
260 case f.Kind != 'd':
261 add(p, CodeLink, "replace "+at+" with a folder")
262 return false
263 }
264 if f.UID != in.UID || f.Owner != "" && f.Owner != in.User && f.Owner != strconv.Itoa(in.UID) {
265 add(p, CodeOwner, "sudo chown "+in.User+" "+at+" (an administrator)")
266 }
267 switch {
268 case root && f.Perm&0o077 != 0 && p == home:
269 add(p, CodeHomeMode, "chmod 700 ~")
270 case root && f.Perm&0o077 != 0:
271 add(p, CodeMode, "chmod 700 "+at)
272 case !root && f.Perm&0o022 != 0:
273 add(p, CodeMode, "chmod go-w "+at)
274 }
275 // Highest index first, so each removal leaves the next one's
276 // number as printed.
277 for i := len(f.ACL) - 1; i >= 0; i-- {
278 if e := f.ACL[i]; e.Allow && e.Who != "user:"+in.User {
279 add(p, CodeACL, "chmod -a# "+strconv.Itoa(e.Index)+" "+at)
280 }
281 }
282 usable[p] = true
283 return true
284 }
285 look(home)
286 for _, root := range in.Roots {
287 p := filepath.Clean(root)
288 if !filepath.IsAbs(root) || !within(home, p) {
289 add(p, CodeOutside, "keep "+p+" inside ~")
290 continue
291 }
292 rel, _ := strings.CutPrefix(p, home)
293 parts := strings.Split(strings.Trim(rel, "/"), "/")
294 ok := true
295 for i := 1; i < len(parts) && ok; i++ {
296 ok = look(filepath.Join(append([]string{home}, parts[:i]...)...))
297 }
298 if ok && p != home {
299 look(p)
300 }
301 }
302 return r
303}
304
305// tilde is p with the home written ~.
306func tilde(home, p string) string {
307 if p == home {
308 return "~"
309 }
310 if rel, ok := strings.CutPrefix(p, home+"/"); ok {
311 return "~/" + rel
312 }
313 return p
314}
315
316// within: p is home or below it (both clean and absolute).
317func within(home, p string) bool {
318 return p == home || strings.HasPrefix(p, home+"/")
319}
320
321// bootStandIn stands in for this machine's boot in a test build
322// (BootForTest); nil in every other build.
323var bootStandIn func() (proc.Boot, error)
324
325// Boot is this boot: its identity (BootID) and when it began (BootTime).
326func Boot() (proc.Boot, error) {
327 if bootStandIn != nil {
328 return bootStandIn()
329 }
330 t, err := BootTime()
331 if err != nil {
332 return proc.Boot{}, err
333 }
334 id, err := BootID()
335 if err != nil {
336 return proc.Boot{}, err
337 }
338 return proc.Boot{ID: id, Time: t}, nil
339}
340