package release import ( "errors" "fmt" "os" "path/filepath" "strconv" "strings" "unicode" "unicode/utf8" "amadan.net/oficina/equipo/internal/wire" ) // The three ways VerifyRenderer can fail, as errors.Is targets. Each // maps to the renderer's health (RendererHealth). var ( ErrRendererMissing = errors.New("renderer missing") ErrRendererMismatch = errors.New("renderer mismatch") ErrRendererUnpinned = errors.New("renderer unpinned") ) // RendererError is why an installed renderer tree is not the pinned one. // Health is wire.ToolMissing (no tree at the path), wire.ToolMismatch (a // tree that differs from the pin, or is unsafe to use) or // wire.ToolUnpinned (no pin to check against). Path is the entry that // differs, relative to the tree ("" for the tree's own directory, // "MANIFEST" for the list). These are diagnostics for logs, not words a // person reads. type RendererError struct { Health string Path string Reason string } func (e *RendererError) Error() string { if e.Path == "" { return fmt.Sprintf("renderer %s: %s", e.Health, e.Reason) } return fmt.Sprintf("renderer %s: %s: %s", e.Health, e.Path, e.Reason) } func (e *RendererError) Unwrap() error { switch e.Health { case wire.ToolMissing: return ErrRendererMissing case wire.ToolUnpinned: return ErrRendererUnpinned } return ErrRendererMismatch } // RendererHealth is the health a VerifyRenderer result reports: ok for // nil, the error's own state for a RendererError, and mismatch for any // other error, so nothing unexpected reads as ok. func RendererHealth(err error) string { if err == nil { return wire.ToolHealthy } var re *RendererError if errors.As(err, &re) && (re.Health == wire.ToolMissing || re.Health == wire.ToolUnpinned) { return re.Health } return wire.ToolMismatch } func rendererMismatch(path, format string, args ...any) error { return &RendererError{Health: wire.ToolMismatch, Path: path, Reason: fmt.Sprintf(format, args...)} } // The real MANIFEST is about 250 KiB (2,316 entries); anything near this // is not one the build wrote. const rendererManifestMax = 16 << 20 // VerifyRenderer checks that dir, an absolute and clean path, holds // exactly the renderer tree pin names: pin is the SHA-256 of the tree's // MANIFEST (release.rendererSHA256), and MANIFEST lists every entry // (scripts/build-renderer-tree.py writes it). Every entry must exist with // its listed type, hash and mode, every link must hold exactly its listed // target, nothing else may be in the tree but MANIFEST, and nothing (the // tree's directory, MANIFEST, any entry) may be group or world writable, // owned by anyone but this user or root, or (files) linked from anywhere // else. Nothing is followed: a link where the MANIFEST lists a file or a // directory is a mismatch. // // It returns nil, or a *RendererError whose Health is unpinned when pin // is not a SHA-256 (checked before the disk is read), missing when dir // does not exist, and mismatch otherwise. // // The check holds for the moment it runs. The tree stays as checked only // because nobody but this user and root can write it, which the check // makes sure of; a change by those after the check is out of its reach. func VerifyRenderer(dir, pin string) error { if !sha256Hex(pin) { return &RendererError{Health: wire.ToolUnpinned, Reason: "no renderer pin is linked into this runner"} } if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { return rendererMismatch("", "%q is not an absolute, clean path", dir) } return verifyRendererTree(dir, pin, uint32(os.Geteuid())) } // rendererEntry is one MANIFEST line: kind "dir", "file" (sha256, mode) // or "link" (target). type rendererEntry struct { kind, sha256, target string mode uint32 } // rendererLinkDepth bounds the links followed resolving one target, as // the build script's LINK_DEPTH does. const rendererLinkDepth = 40 // parseRendererManifest reads a MANIFEST strictly: lines of // "dir ", "file " or "link ", // fields split by one space, each line ending in a newline, sorted by // path with no duplicate, every parent listed as a dir before its // children. A path is relative and clean (no empty, "." or ".." part), // a hash is lower-case hex, a mode is four octal digits with no // group or world write, setuid, setgid or sticky bit. A link's target is // relative and resolves, through any links on the way, to an entry of // the tree without climbing out of it. Anything else is refused. func parseRendererManifest(b []byte) (map[string]rendererEntry, error) { entries := map[string]rendererEntry{} if len(b) == 0 { return entries, nil } if !utf8.Valid(b) { return nil, errors.New("MANIFEST is not UTF-8") } if b[len(b)-1] != '\n' { return nil, errors.New("MANIFEST does not end in a newline") } prev := "" for i, line := range strings.Split(string(b[:len(b)-1]), "\n") { fields := strings.Split(line, " ") bad := func(why string) error { return fmt.Errorf("MANIFEST line %d %q: %s", i+1, line, why) } if len(fields) < 2 { return nil, bad("not an entry") } kind, path := fields[0], fields[1] e := rendererEntry{kind: kind} switch { case kind == "dir" && len(fields) == 2: case kind == "file" && len(fields) == 4: if !sha256Hex(fields[2]) { return nil, bad("not a SHA-256") } mode, ok := rendererMode(fields[3]) if !ok { return nil, bad("not a mode the tree may hold") } e.sha256, e.mode = fields[2], mode case kind == "link" && len(fields) == 3: if !manifestField(fields[2]) || strings.HasPrefix(fields[2], "/") { return nil, bad("not a relative link target") } e.target = fields[2] case kind == "dir" || kind == "file" || kind == "link": return nil, bad("wrong number of fields") default: return nil, bad("unknown kind") } if !rendererPath(path) { return nil, bad("not a clean relative path") } if i > 0 && path <= prev { return nil, bad("not sorted after " + prev) } if slash := strings.LastIndexByte(path, '/'); slash >= 0 { if entries[path[:slash]].kind != "dir" { return nil, bad("its directory is not listed") } } entries[path], prev = e, path } for path, e := range entries { if e.kind == "link" { parent := strings.Split(path, "/") if _, err := resolveRendererLink(entries, parent[:len(parent)-1], e.target, 0); err != nil { return nil, fmt.Errorf("MANIFEST link %s -> %s: %w", path, e.target, err) } } } return entries, nil } // resolveRendererLink is where target, read in directory here (names // from the tree's root), leads: names from the root, each step an entry // of the tree, never above the root. As Linux resolves a path, every // part after the first, including an empty or "." part (a trailing "/" // or "/."), needs a directory before it: "f/" and "f/." fail when f is a // file. It mirrors the build script's Tree.resolve. func resolveRendererLink(entries map[string]rendererEntry, here []string, target string, depth int) ([]string, error) { if depth > rendererLinkDepth { return nil, errors.New("too many links") } here = append([]string(nil), here...) for i, name := range strings.Split(target, "/") { if i > 0 && len(here) > 0 && entries[strings.Join(here, "/")].kind != "dir" { return nil, fmt.Errorf("%s is not a directory", strings.Join(here, "/")) } switch name { case "", ".": continue case "..": if len(here) == 0 { return nil, errors.New("climbs out of the tree") } here = here[:len(here)-1] continue } path := name if len(here) > 0 { path = strings.Join(here, "/") + "/" + name } e, ok := entries[path] if !ok { return nil, fmt.Errorf("%s names nothing in the tree", path) } if e.kind == "link" { next, err := resolveRendererLink(entries, here, e.target, depth+1) if err != nil { return nil, err } here = next } else { here = append(here, name) } } return here, nil } // rendererPath is a MANIFEST path: relative, clean, holdable, and not // MANIFEST itself. An absolute path has an empty first part. func rendererPath(p string) bool { if !manifestField(p) || p == "MANIFEST" { return false } for _, part := range strings.Split(p, "/") { if part == "" || part == "." || part == ".." { return false } } return true } // manifestField is what one MANIFEST field can hold, as the build // script's holdable: not empty, no white space or control characters. // (The whole MANIFEST is checked to be UTF-8 first.) Above U+0020, // unicode.IsSpace and Python's str.isspace agree. func manifestField(s string) bool { if s == "" { return false } for _, r := range s { if r < 0x20 || r == 0x7f || unicode.IsSpace(r) { return false } } return true } // rendererMode parses a file mode as the MANIFEST writes it ("0644"): // four octal digits, permission bits only, nothing group or world // writable. func rendererMode(s string) (uint32, bool) { if len(s) != 4 || s[0] != '0' || strings.ContainsFunc(s, func(r rune) bool { return r < '0' || r > '7' }) { return 0, false } m, err := strconv.ParseUint(s, 8, 32) if err != nil || m&0o022 != 0 { return 0, false } return uint32(m), true }