// Package creds is a Mac worker's Claude credential guards (Mac runners // spec §8.3, §8.7; slice F task 10): the home guard, which decides from // ownership, mode bits and ACLs whether anyone else could reach the // folders a connection lives in, and the Keychain watch around a // sign-in. It reads facts through seams (ls -led and lstat, security // dump-keychain), so everything here is tested with recorded outputs. package creds import ( "errors" "io/fs" "os" "path/filepath" "regexp" "slices" "strconv" "strings" "syscall" "amadan.net/oficina/equipo/internal/runner/mac/proc" ) // ACE is one access control entry as ls -le prints it: // " 0: user:vicky inherited allow read,write". type ACE struct { Index int Who string Inherited bool Allow bool Rights []string } // Fact is what the guard knows of one path: its kind ('d' a directory, // 'l' a link, '-' a file), its permission bits, its owner (the name ls // prints and the uid lstat reads, -1 unknown) and its ACL entries. type Fact struct { Path string Kind byte Perm fs.FileMode Owner string UID int ACL []ACE Missing bool } var ( lsHeader = regexp.MustCompile(`^([-dlbcps])([-rwxsStT]{9})([@+]?)\s+\d+\s+(\S+)\s+(\S+)\s+\d+\s+\S+\s+\S+\s+\S+\s+(.+)$`) lsEntry = regexp.MustCompile(`^\s*(\d+): (\S+) (inherited )?(allow|deny) ([a-z_]+(?:,[a-z_]+)*)$`) ) // ErrUnreadable: ls output the guard cannot read for sure. It decides // nothing from it. var ErrUnreadable = errors.New("creds: ls output not understood") // ParseLS reads `ls -led` output: each path's line and the ACL entries // under it. A line it does not understand, or a "+" with no entry, is // ErrUnreadable. func ParseLS(out string) ([]Fact, error) { var facts []Fact plus := false end := func() error { if len(facts) > 0 && plus && len(facts[len(facts)-1].ACL) == 0 { return ErrUnreadable } return nil } for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") { if line == "" { continue } if m := lsEntry.FindStringSubmatch(line); m != nil { if len(facts) == 0 { return nil, ErrUnreadable } f := &facts[len(facts)-1] n, _ := strconv.Atoi(m[1]) if n != len(f.ACL) { return nil, ErrUnreadable } f.ACL = append(f.ACL, ACE{Index: n, Who: m[2], Inherited: m[3] != "", Allow: m[4] == "allow", Rights: strings.Split(m[5], ",")}) continue } m := lsHeader.FindStringSubmatch(line) if m == nil { return nil, ErrUnreadable } if err := end(); err != nil { return nil, err } path := m[6] if m[1] == "l" { path, _, _ = strings.Cut(path, " -> ") } facts = append(facts, Fact{Path: path, Kind: m[1][0], Perm: permOf(m[2]), Owner: m[4], UID: -1}) plus = m[3] == "+" } if err := end(); err != nil { return nil, err } return facts, nil } // permOf is the 0777 bits of an ls mode string ("rwxr-x---"): s and t // carry x, S and T do not. func permOf(s string) fs.FileMode { var p fs.FileMode for i, c := range s { if c != '-' && c != 'S' && c != 'T' { p |= 1 << (8 - i) } } return p } // Read is path's fact: the kind, mode and owner lstat reads (never // following a link), and, when ls is set, the ACL `ls -led` prints, its // mode and owner required to agree. ls nil (off a Mac) reads no ACL. func Read(path string, ls func(string) (string, error)) (Fact, error) { info, err := os.Lstat(path) if errors.Is(err, fs.ErrNotExist) { return Fact{Path: path, Missing: true, UID: -1}, nil } if err != nil { return Fact{}, err } f := Fact{Path: path, Kind: '-', Perm: info.Mode().Perm(), UID: -1} switch { case info.Mode()&fs.ModeSymlink != 0: f.Kind = 'l' case info.IsDir(): f.Kind = 'd' case !info.Mode().IsRegular(): f.Kind = '?' } if st, ok := info.Sys().(*syscall.Stat_t); ok { f.UID = int(st.Uid) } if ls == nil { return f, nil } out, err := ls(path) if err != nil { return Fact{}, err } facts, err := ParseLS(out) if err != nil || len(facts) != 1 || facts[0].Path != path || facts[0].Kind != f.Kind || facts[0].Perm != f.Perm { return Fact{}, ErrUnreadable } f.Owner, f.ACL = facts[0].Owner, facts[0].ACL return f, nil } // Problem codes: what is wrong, in the capability string rules (the // Engineering status's reason). const ( CodeHomeMode = "home_mode" CodeMode = "mode" CodeACL = "acl" CodeOwner = "owner" CodeOutside = "outside" CodeLink = "link" CodeMissing = "missing" CodeUnknown = "unknown" ) // Input is what the guard checks: the runner user (name and uid), its // home, and the roots that must be private inside it (the state dir, // the config dir, the accounts root). type Input struct { User string UID int Home string Roots []string } // Problem is one thing to change: the path, the code, and the command // that changes it, run as the runner user unless it says otherwise. type Problem struct { Path, Code, Fix string } // Result is the guard's verdict: no problem passes. type Result struct { Problems []Problem } // OK: nobody else can list, traverse, read or replace any root. func (r Result) OK() bool { return len(r.Problems) == 0 } // Reason is the first problem's code, "" when it passes. func (r Result) Reason() string { if r.OK() { return "" } return r.Problems[0].Code } // Fix is every change to make, in order, one per line. func (r Result) Fix() string { var out []string for _, p := range r.Problems { if !slices.Contains(out, p.Fix) { out = append(out, p.Fix) } } return strings.Join(out, "\n") } // Check decides from ownership, mode bits and ACLs alone, through read, // never by opening anything as this user (which cannot see what another // user sees). It passes only when the home and every root are real // directories inside the home, owned by the user, with no group or other // bit and no ACL entry allowing anyone else anything (inherited or not), // and every directory between the home and a root is a real directory // the user owns, with no group or other write bit and no such entry. func Check(in Input, read func(string) (Fact, error)) Result { var r Result home := filepath.Clean(in.Home) add := func(p, code, fix string) { r.Problems = append(r.Problems, Problem{Path: p, Code: code, Fix: fix}) } if !filepath.IsAbs(in.Home) || home == "/" || in.User == "" || in.UID < 0 { add(in.Home, CodeUnknown, "the runner user's home could not be checked") return r } // The protected set first: a root is held to the root rule however // it is reached, as another root's ancestor or as itself. Facts are // read once; each path's problems are said once. protected := map[string]bool{home: true} for _, root := range in.Roots { if p := filepath.Clean(root); filepath.IsAbs(root) && within(home, p) { protected[p] = true } } facts := map[string]Fact{} errs := map[string]error{} usable := map[string]bool{} done := map[string]bool{} look := func(p string) bool { if done[p] { return usable[p] } done[p] = true f, ok := facts[p] if !ok { f, errs[p] = read(p) facts[p] = f } root, at := protected[p], tilde(home, p) switch { case errs[p] != nil: add(p, CodeUnknown, at+" could not be checked") return false case f.Missing: add(p, CodeMissing, "mkdir -m 700 "+at) return false case f.Kind == 'l': add(p, CodeLink, "replace the link "+at+" with a folder") return false case f.Kind != 'd': add(p, CodeLink, "replace "+at+" with a folder") return false } if f.UID != in.UID || f.Owner != "" && f.Owner != in.User && f.Owner != strconv.Itoa(in.UID) { add(p, CodeOwner, "sudo chown "+in.User+" "+at+" (an administrator)") } switch { case root && f.Perm&0o077 != 0 && p == home: add(p, CodeHomeMode, "chmod 700 ~") case root && f.Perm&0o077 != 0: add(p, CodeMode, "chmod 700 "+at) case !root && f.Perm&0o022 != 0: add(p, CodeMode, "chmod go-w "+at) } // Highest index first, so each removal leaves the next one's // number as printed. for i := len(f.ACL) - 1; i >= 0; i-- { if e := f.ACL[i]; e.Allow && e.Who != "user:"+in.User { add(p, CodeACL, "chmod -a# "+strconv.Itoa(e.Index)+" "+at) } } usable[p] = true return true } look(home) for _, root := range in.Roots { p := filepath.Clean(root) if !filepath.IsAbs(root) || !within(home, p) { add(p, CodeOutside, "keep "+p+" inside ~") continue } rel, _ := strings.CutPrefix(p, home) parts := strings.Split(strings.Trim(rel, "/"), "/") ok := true for i := 1; i < len(parts) && ok; i++ { ok = look(filepath.Join(append([]string{home}, parts[:i]...)...)) } if ok && p != home { look(p) } } return r } // tilde is p with the home written ~. func tilde(home, p string) string { if p == home { return "~" } if rel, ok := strings.CutPrefix(p, home+"/"); ok { return "~/" + rel } return p } // within: p is home or below it (both clean and absolute). func within(home, p string) bool { return p == home || strings.HasPrefix(p, home+"/") } // bootStandIn stands in for this machine's boot in a test build // (BootForTest); nil in every other build. var bootStandIn func() (proc.Boot, error) // Boot is this boot: its identity (BootID) and when it began (BootTime). func Boot() (proc.Boot, error) { if bootStandIn != nil { return bootStandIn() } t, err := BootTime() if err != nil { return proc.Boot{}, err } id, err := BootID() if err != nil { return proc.Boot{}, err } return proc.Boot{ID: id, Time: t}, nil }