| 1 | package release |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "unicode" |
| 11 | "unicode/utf8" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/wire" |
| 14 | ) |
| 15 | |
| 16 | // The three ways VerifyRenderer can fail, as errors.Is targets. Each |
| 17 | // maps to the renderer's health (RendererHealth). |
| 18 | var ( |
| 19 | ErrRendererMissing = errors.New("renderer missing") |
| 20 | ErrRendererMismatch = errors.New("renderer mismatch") |
| 21 | ErrRendererUnpinned = errors.New("renderer unpinned") |
| 22 | ) |
| 23 | |
| 24 | // RendererError is why an installed renderer tree is not the pinned one. |
| 25 | // Health is wire.ToolMissing (no tree at the path), wire.ToolMismatch (a |
| 26 | // tree that differs from the pin, or is unsafe to use) or |
| 27 | // wire.ToolUnpinned (no pin to check against). Path is the entry that |
| 28 | // differs, relative to the tree ("" for the tree's own directory, |
| 29 | // "MANIFEST" for the list). These are diagnostics for logs, not words a |
| 30 | // person reads. |
| 31 | type RendererError struct { |
| 32 | Health string |
| 33 | Path string |
| 34 | Reason string |
| 35 | } |
| 36 | |
| 37 | func (e *RendererError) Error() string { |
| 38 | if e.Path == "" { |
| 39 | return fmt.Sprintf("renderer %s: %s", e.Health, e.Reason) |
| 40 | } |
| 41 | return fmt.Sprintf("renderer %s: %s: %s", e.Health, e.Path, e.Reason) |
| 42 | } |
| 43 | |
| 44 | func (e *RendererError) Unwrap() error { |
| 45 | switch e.Health { |
| 46 | case wire.ToolMissing: |
| 47 | return ErrRendererMissing |
| 48 | case wire.ToolUnpinned: |
| 49 | return ErrRendererUnpinned |
| 50 | } |
| 51 | return ErrRendererMismatch |
| 52 | } |
| 53 | |
| 54 | // RendererHealth is the health a VerifyRenderer result reports: ok for |
| 55 | // nil, the error's own state for a RendererError, and mismatch for any |
| 56 | // other error, so nothing unexpected reads as ok. |
| 57 | func RendererHealth(err error) string { |
| 58 | if err == nil { |
| 59 | return wire.ToolHealthy |
| 60 | } |
| 61 | var re *RendererError |
| 62 | if errors.As(err, &re) && (re.Health == wire.ToolMissing || re.Health == wire.ToolUnpinned) { |
| 63 | return re.Health |
| 64 | } |
| 65 | return wire.ToolMismatch |
| 66 | } |
| 67 | |
| 68 | func rendererMismatch(path, format string, args ...any) error { |
| 69 | return &RendererError{Health: wire.ToolMismatch, Path: path, Reason: fmt.Sprintf(format, args...)} |
| 70 | } |
| 71 | |
| 72 | // The real MANIFEST is about 250 KiB (2,316 entries); anything near this |
| 73 | // is not one the build wrote. |
| 74 | const rendererManifestMax = 16 << 20 |
| 75 | |
| 76 | // VerifyRenderer checks that dir, an absolute and clean path, holds |
| 77 | // exactly the renderer tree pin names: pin is the SHA-256 of the tree's |
| 78 | // MANIFEST (release.rendererSHA256), and MANIFEST lists every entry |
| 79 | // (scripts/build-renderer-tree.py writes it). Every entry must exist with |
| 80 | // its listed type, hash and mode, every link must hold exactly its listed |
| 81 | // target, nothing else may be in the tree but MANIFEST, and nothing (the |
| 82 | // tree's directory, MANIFEST, any entry) may be group or world writable, |
| 83 | // owned by anyone but this user or root, or (files) linked from anywhere |
| 84 | // else. Nothing is followed: a link where the MANIFEST lists a file or a |
| 85 | // directory is a mismatch. |
| 86 | // |
| 87 | // It returns nil, or a *RendererError whose Health is unpinned when pin |
| 88 | // is not a SHA-256 (checked before the disk is read), missing when dir |
| 89 | // does not exist, and mismatch otherwise. |
| 90 | // |
| 91 | // The check holds for the moment it runs. The tree stays as checked only |
| 92 | // because nobody but this user and root can write it, which the check |
| 93 | // makes sure of; a change by those after the check is out of its reach. |
| 94 | func VerifyRenderer(dir, pin string) error { |
| 95 | if !sha256Hex(pin) { |
| 96 | return &RendererError{Health: wire.ToolUnpinned, Reason: "no renderer pin is linked into this runner"} |
| 97 | } |
| 98 | if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { |
| 99 | return rendererMismatch("", "%q is not an absolute, clean path", dir) |
| 100 | } |
| 101 | return verifyRendererTree(dir, pin, uint32(os.Geteuid())) |
| 102 | } |
| 103 | |
| 104 | // rendererEntry is one MANIFEST line: kind "dir", "file" (sha256, mode) |
| 105 | // or "link" (target). |
| 106 | type rendererEntry struct { |
| 107 | kind, sha256, target string |
| 108 | mode uint32 |
| 109 | } |
| 110 | |
| 111 | // rendererLinkDepth bounds the links followed resolving one target, as |
| 112 | // the build script's LINK_DEPTH does. |
| 113 | const rendererLinkDepth = 40 |
| 114 | |
| 115 | // parseRendererManifest reads a MANIFEST strictly: lines of |
| 116 | // "dir <path>", "file <path> <sha256> <mode>" or "link <path> <target>", |
| 117 | // fields split by one space, each line ending in a newline, sorted by |
| 118 | // path with no duplicate, every parent listed as a dir before its |
| 119 | // children. A path is relative and clean (no empty, "." or ".." part), |
| 120 | // a hash is lower-case hex, a mode is four octal digits with no |
| 121 | // group or world write, setuid, setgid or sticky bit. A link's target is |
| 122 | // relative and resolves, through any links on the way, to an entry of |
| 123 | // the tree without climbing out of it. Anything else is refused. |
| 124 | func parseRendererManifest(b []byte) (map[string]rendererEntry, error) { |
| 125 | entries := map[string]rendererEntry{} |
| 126 | if len(b) == 0 { |
| 127 | return entries, nil |
| 128 | } |
| 129 | if !utf8.Valid(b) { |
| 130 | return nil, errors.New("MANIFEST is not UTF-8") |
| 131 | } |
| 132 | if b[len(b)-1] != '\n' { |
| 133 | return nil, errors.New("MANIFEST does not end in a newline") |
| 134 | } |
| 135 | prev := "" |
| 136 | for i, line := range strings.Split(string(b[:len(b)-1]), "\n") { |
| 137 | fields := strings.Split(line, " ") |
| 138 | bad := func(why string) error { return fmt.Errorf("MANIFEST line %d %q: %s", i+1, line, why) } |
| 139 | if len(fields) < 2 { |
| 140 | return nil, bad("not an entry") |
| 141 | } |
| 142 | kind, path := fields[0], fields[1] |
| 143 | e := rendererEntry{kind: kind} |
| 144 | switch { |
| 145 | case kind == "dir" && len(fields) == 2: |
| 146 | case kind == "file" && len(fields) == 4: |
| 147 | if !sha256Hex(fields[2]) { |
| 148 | return nil, bad("not a SHA-256") |
| 149 | } |
| 150 | mode, ok := rendererMode(fields[3]) |
| 151 | if !ok { |
| 152 | return nil, bad("not a mode the tree may hold") |
| 153 | } |
| 154 | e.sha256, e.mode = fields[2], mode |
| 155 | case kind == "link" && len(fields) == 3: |
| 156 | if !manifestField(fields[2]) || strings.HasPrefix(fields[2], "/") { |
| 157 | return nil, bad("not a relative link target") |
| 158 | } |
| 159 | e.target = fields[2] |
| 160 | case kind == "dir" || kind == "file" || kind == "link": |
| 161 | return nil, bad("wrong number of fields") |
| 162 | default: |
| 163 | return nil, bad("unknown kind") |
| 164 | } |
| 165 | if !rendererPath(path) { |
| 166 | return nil, bad("not a clean relative path") |
| 167 | } |
| 168 | if i > 0 && path <= prev { |
| 169 | return nil, bad("not sorted after " + prev) |
| 170 | } |
| 171 | if slash := strings.LastIndexByte(path, '/'); slash >= 0 { |
| 172 | if entries[path[:slash]].kind != "dir" { |
| 173 | return nil, bad("its directory is not listed") |
| 174 | } |
| 175 | } |
| 176 | entries[path], prev = e, path |
| 177 | } |
| 178 | for path, e := range entries { |
| 179 | if e.kind == "link" { |
| 180 | parent := strings.Split(path, "/") |
| 181 | if _, err := resolveRendererLink(entries, parent[:len(parent)-1], e.target, 0); err != nil { |
| 182 | return nil, fmt.Errorf("MANIFEST link %s -> %s: %w", path, e.target, err) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | return entries, nil |
| 187 | } |
| 188 | |
| 189 | // resolveRendererLink is where target, read in directory here (names |
| 190 | // from the tree's root), leads: names from the root, each step an entry |
| 191 | // of the tree, never above the root. As Linux resolves a path, every |
| 192 | // part after the first, including an empty or "." part (a trailing "/" |
| 193 | // or "/."), needs a directory before it: "f/" and "f/." fail when f is a |
| 194 | // file. It mirrors the build script's Tree.resolve. |
| 195 | func resolveRendererLink(entries map[string]rendererEntry, here []string, target string, depth int) ([]string, error) { |
| 196 | if depth > rendererLinkDepth { |
| 197 | return nil, errors.New("too many links") |
| 198 | } |
| 199 | here = append([]string(nil), here...) |
| 200 | for i, name := range strings.Split(target, "/") { |
| 201 | if i > 0 && len(here) > 0 && entries[strings.Join(here, "/")].kind != "dir" { |
| 202 | return nil, fmt.Errorf("%s is not a directory", strings.Join(here, "/")) |
| 203 | } |
| 204 | switch name { |
| 205 | case "", ".": |
| 206 | continue |
| 207 | case "..": |
| 208 | if len(here) == 0 { |
| 209 | return nil, errors.New("climbs out of the tree") |
| 210 | } |
| 211 | here = here[:len(here)-1] |
| 212 | continue |
| 213 | } |
| 214 | path := name |
| 215 | if len(here) > 0 { |
| 216 | path = strings.Join(here, "/") + "/" + name |
| 217 | } |
| 218 | e, ok := entries[path] |
| 219 | if !ok { |
| 220 | return nil, fmt.Errorf("%s names nothing in the tree", path) |
| 221 | } |
| 222 | if e.kind == "link" { |
| 223 | next, err := resolveRendererLink(entries, here, e.target, depth+1) |
| 224 | if err != nil { |
| 225 | return nil, err |
| 226 | } |
| 227 | here = next |
| 228 | } else { |
| 229 | here = append(here, name) |
| 230 | } |
| 231 | } |
| 232 | return here, nil |
| 233 | } |
| 234 | |
| 235 | // rendererPath is a MANIFEST path: relative, clean, holdable, and not |
| 236 | // MANIFEST itself. An absolute path has an empty first part. |
| 237 | func rendererPath(p string) bool { |
| 238 | if !manifestField(p) || p == "MANIFEST" { |
| 239 | return false |
| 240 | } |
| 241 | for _, part := range strings.Split(p, "/") { |
| 242 | if part == "" || part == "." || part == ".." { |
| 243 | return false |
| 244 | } |
| 245 | } |
| 246 | return true |
| 247 | } |
| 248 | |
| 249 | // manifestField is what one MANIFEST field can hold, as the build |
| 250 | // script's holdable: not empty, no white space or control characters. |
| 251 | // (The whole MANIFEST is checked to be UTF-8 first.) Above U+0020, |
| 252 | // unicode.IsSpace and Python's str.isspace agree. |
| 253 | func manifestField(s string) bool { |
| 254 | if s == "" { |
| 255 | return false |
| 256 | } |
| 257 | for _, r := range s { |
| 258 | if r < 0x20 || r == 0x7f || unicode.IsSpace(r) { |
| 259 | return false |
| 260 | } |
| 261 | } |
| 262 | return true |
| 263 | } |
| 264 | |
| 265 | // rendererMode parses a file mode as the MANIFEST writes it ("0644"): |
| 266 | // four octal digits, permission bits only, nothing group or world |
| 267 | // writable. |
| 268 | func rendererMode(s string) (uint32, bool) { |
| 269 | if len(s) != 4 || s[0] != '0' || strings.ContainsFunc(s, func(r rune) bool { return r < '0' || r > '7' }) { |
| 270 | return 0, false |
| 271 | } |
| 272 | m, err := strconv.ParseUint(s, 8, 32) |
| 273 | if err != nil || m&0o022 != 0 { |
| 274 | return 0, false |
| 275 | } |
| 276 | return uint32(m), true |
| 277 | } |
| 278 | |