1use super::*;
3use std::{collections::BTreeMap, path::Path, process::Command, time::Duration};
4
5pub const WARNING: &str = "Installs one Homebrew core formula at its current version, not a fixed version. Formula, build and dependency code can run. Dependencies can be installed or upgraded, and links can add commands to PATH. No sandbox or rollback. A 10-minute deadline can leave partial effects.";
6const CONTROLS: &[&str] = &[
7 "HOMEBREW_NO_AUTO_UPDATE",
8 "HOMEBREW_NO_ANALYTICS",
9 "HOMEBREW_NO_ENV_HINTS",
10 "HOMEBREW_NO_INSTALL_UPGRADE",
11 "HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK",
12 "HOMEBREW_NO_INSTALL_CLEANUP",
13];
14#[derive(Clone, Serialize, Deserialize)]
15#[serde(deny_unknown_fields)]
16pub struct Probe {
17 pub required_controls_advertised: bool,
18 pub prefix: PathBuf,
19 pub repository: PathBuf,
20 pub cellar: PathBuf,
21 pub stable_version: String,
22 pub installed_versions: Vec<String>,
23}
24impl Probe {
25 pub(super) fn valid(&self, b: &Scope) -> bool {
26 self.required_controls_advertised
27 && self.prefix == b.prefix
28 && self.repository == b.repository
29 && self.cellar == b.cellar
30 && super::super::valid_observed_version(&self.stable_version)
31 && self.installed_versions.len() <= 256
32 && self
33 .installed_versions
34 .iter()
35 .all(|v| super::super::valid_observed_version(v) && !v.starts_with("HEAD"))
36 }
37}
38#[derive(Clone, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct Scope {
41 pub prefix: PathBuf,
42 pub repository: PathBuf,
43 pub cellar: PathBuf,
44 pub policy: VersionPolicy,
45 pub catalogs: Vec<npm::Catalog>,
46}
47pub fn prefix_hint(executable: &Path) -> Option<PathBuf> {
49 let repo = repository(executable)?;
50 Some(if repo.file_name()? == "Homebrew" {
51 repo.parent()?.to_owned()
52 } else {
53 repo
54 })
55}
56fn repository(executable: &Path) -> Option<PathBuf> {
57 (executable.file_name()? == "brew" && executable.parent()?.file_name()? == "bin")
58 .then(|| {
59 executable
60 .parent()
61 .and_then(Path::parent)
62 .map(Path::to_owned)
63 })
64 .flatten()
65}
66pub fn formula(package: &str) -> bool {
69 !package.is_empty()
70 && package.len() <= 128
71 && package.as_bytes()[0].is_ascii_lowercase()
72 && package
73 .bytes()
74 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"+._-@".contains(&b))
75 && !package.contains("..")
76}
77pub(super) fn valid(s: &super::Scope) -> bool {
78 let Some(b) = &s.brew else {
79 return false;
80 };
81 s.npm.is_none()
82 && formula(&s.package)
83 && matches!(
84 b.policy,
85 VersionPolicy::ProviderDefault {} | VersionPolicy::Latest {}
86 )
87 && s.version
88 == if matches!(b.policy, VersionPolicy::Latest {}) {
89 "latest"
90 } else {
91 "provider_default"
92 }
93 && inspection::absolute(&b.prefix)
94 && b.prefix.ancestors().count() <= 32
95 && b.prefix != Path::new("/")
96 && b.cellar == b.prefix.join("Cellar")
97 && repository(&s.executable).as_ref() == Some(&b.repository)
98 && (b.repository == b.prefix || b.repository == b.prefix.join("Homebrew"))
99 && valid_catalogs(s, b)
100}
101fn valid_catalogs(s: &super::Scope, b: &Scope) -> bool {
102 let mut ids = BTreeSet::new();
103 !b.catalogs.is_empty()
104 && b.catalogs.len() <= 16
105 && b.catalogs.iter().all(|c| {
106 !c.tools.is_empty()
107 && c.tools.len() <= 256
108 && c.search_dirs.len() <= 256
109 && c.preview(&s.home).is_ok()
110 && c.tools.iter().all(|id| ids.insert(id.clone()))
111 && (!c.tools.contains(&s.tool)
112 || (c.query == inspection::Query::BrewFormulae
113 && c.executable == s.executable
114 && c.search_dirs == s.search_dirs))
115 })
116 && ids == s.bound_tools
117}
118pub fn prepare(
119 host: &HostContext,
120 request: Request,
121 brew: Scope,
122 reports: &[&inspection::Report],
123) -> Result<Preview> {
124 let (manifest, scope, sources) = super::sources(host, &request, None, Some(&brew))?;
125 super::bounded_metadata(&scope, &sources)?;
126 catalogs(&scope, &brew, reports)?;
127 let row = super::evaluate_catalogs(host, &manifest, &scope, reports)?;
128 if row.action != planning::PackageAction::ReviewMissingPackage || !row.blockers.is_empty() {
129 return Err(invalid(
130 "only an observed missing canonical core formula with clear explicit prerequisites can be reviewed",
131 ));
132 }
133 Ok(Preview {
134 request,
135 scope,
136 sources,
137 })
138}
139pub(super) fn catalogs<'a>(
140 s: &super::Scope,
141 b: &Scope,
142 reports: &[&'a inspection::Report],
143) -> Result<BTreeMap<String, &'a inspection::Report>> {
144 if b.catalogs.len() != reports.len() {
145 return Err(invalid("Homebrew catalog count differs"));
146 }
147 let mut out = BTreeMap::new();
148 for (c, r) in b.catalogs.iter().zip(reports) {
149 if !c.matches(&s.home, r) {
150 return Err(invalid("Homebrew prerequisite catalog scope differs"));
151 }
152 for id in &c.tools {
153 if out.insert(id.clone(), *r).is_some() {
154 return Err(invalid("duplicate Homebrew catalog binding"));
155 }
156 }
157 }
158 Ok(out)
159}
160#[derive(Clone, Serialize, Deserialize)]
161#[serde(deny_unknown_fields)]
162pub(super) struct Sources {
163 bindings: npm::Sources,
164 parents: Vec<observation::Parent>,
165}
166pub(super) fn same(a: &Sources, b: &Sources) -> bool {
167 npm::same(&a.bindings, &b.bindings)
168 && a.parents.len() == b.parents.len()
169 && a.parents.iter().zip(&b.parents).all(|(a, b)| {
170 a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
171 })
172}
173fn writable_root(
177 owner: u32,
178 group: u32,
179 mode: u32,
180 uid: u32,
181 groups: &[u32],
182 prefix: bool,
183) -> bool {
184 if mode & 0o002 != 0 || (mode & 0o020 != 0 && !groups.contains(&group)) {
185 return false;
186 }
187 (owner == uid || (prefix && owner == 0)) && mode & 0o200 != 0
188}
189fn safe_parent(fingerprint: &observation::Fingerprint, uid: u32, groups: &[u32]) -> bool {
190 if fingerprint.mode & 0o002 != 0
191 || (fingerprint.mode & 0o020 != 0 && !groups.contains(&fingerprint.gid))
192 {
193 return false;
194 }
195 fingerprint.uid == uid || fingerprint.uid == 0
196}
197fn caller_groups() -> Vec<u32> {
198 let mut groups: Vec<u32> = rustix::process::getgroups()
199 .unwrap_or_default()
200 .iter()
201 .map(|g| g.as_raw())
202 .collect();
203 groups.push(rustix::process::getegid().as_raw());
204 groups.sort_unstable();
205 groups.dedup();
206 groups
207}
208pub(super) fn sources(s: &super::Scope) -> Result<Sources> {
209 let b = s.brew.as_ref().expect("brew scope");
210 let mut programs = vec![npm::program(&s.executable, true)?];
211 for c in &b.catalogs {
212 programs.push(npm::program(&c.executable, true)?);
213 if let Some(n) = &c.npm_binding {
214 programs.push(npm::program(&n.npm_cli, false)?);
215 }
216 }
217 let mut paths = BTreeSet::from([
220 b.prefix.clone(),
221 b.repository.clone(),
222 b.repository.join("Library"),
223 ]);
224 for root in [
225 "Cellar",
226 "bin",
227 "etc",
228 "include",
229 "lib",
230 "opt",
231 "sbin",
232 "share",
233 "var",
234 "var/homebrew",
235 ] {
236 paths.insert(b.prefix.join(root));
237 }
238 let uid = rustix::process::geteuid().as_raw();
239 let groups = caller_groups();
240 let directories = paths.into_iter().map(|path| {
241 let e = observation::inspect(&path, false)?;
242 if e.kind != Kind::Directory {
243 return Err(scope_invalid(format!(
244 "Homebrew folder {path:?} is missing or is not a real folder."
245 )));
246 }
247 let Some(fingerprint) = e.fingerprint.as_ref() else {
248 return Err(scope_invalid(format!(
249 "Homebrew folder {path:?} cannot be verified."
250 )));
251 };
252 if fingerprint.mode & 0o002 != 0 {
253 return Err(scope_invalid(format!(
254 "Homebrew folder {path:?} is writable by everyone."
255 )));
256 }
257 if fingerprint.mode & 0o020 != 0 && !groups.contains(&fingerprint.gid) {
258 return Err(scope_invalid(format!(
259 "Homebrew folder {path:?} is writable by a group you are not in."
260 )));
261 }
262 if !writable_root(
263 fingerprint.uid,
264 fingerprint.gid,
265 fingerprint.mode,
266 uid,
267 &groups,
268 path == b.prefix,
269 ) {
270 return Err(scope_invalid(format!(
271 "Homebrew folder {path:?} must belong to you and be writable by you."
272 )));
273 }
274 if let Some(parent) = e.parents.iter().find(|p| {
275 (!b.prefix.starts_with(&s.home) || p.path.starts_with(&s.home))
278 && !safe_parent(&p.fingerprint, uid, &groups)
279 }) {
280 return Err(scope_invalid(format!(
281 "Homebrew parent folder {:?} is writable by users outside your account or belongs to another account.",
282 parent.path
283 )));
284 }
285 Ok(e)
286 }).collect::<Result<Vec<_>>>()?;
287 let mut lookup = BTreeSet::new();
288 lookup.extend(s.tool_search_dirs.iter().cloned());
289 lookup.extend(s.search_dirs.iter().cloned());
290 for c in &b.catalogs {
291 lookup.extend(c.search_dirs.iter().cloned());
292 }
293 let tool_directories = lookup
294 .iter()
295 .map(|p| {
296 let e = observation::inspect(p, false)?;
297 if e.kind != Kind::Directory {
298 return Err(invalid("tool search directory unavailable or unsafe"));
299 }
300 Ok(e)
301 })
302 .collect::<Result<Vec<_>>>()?;
303 let mut bindings = npm::Sources {
304 programs,
305 directories,
306 tool_directories,
307 };
308 let mut parents = BTreeMap::<PathBuf, observation::Parent>::new();
311 for e in bindings
312 .programs
313 .iter_mut()
314 .chain(&mut bindings.directories)
315 .chain(&mut bindings.tool_directories)
316 {
317 for p in std::mem::take(&mut e.parents) {
318 if let Some(old) = parents.get(&p.path) {
319 if !adoption::parent_identity(&old.fingerprint, &p.fingerprint) {
320 return Err(invalid("Homebrew parents changed while binding"));
321 }
322 } else {
323 parents.insert(p.path.clone(), p);
324 }
325 }
326 }
327 Ok(Sources {
328 bindings,
329 parents: parents.into_values().collect(),
330 })
331}
332pub(super) fn arguments(package: &str) -> Vec<String> {
333 [
334 "install".into(),
335 "--formula".into(),
336 "--no-ask".into(),
337 "--skip-post-install".into(),
338 format!("homebrew/core/{package}"),
339 ]
340 .into()
341}
342pub(super) fn probe_arguments(package: &str) -> Vec<Vec<String>> {
343 vec![
344 vec!["help".into(), "install".into()],
345 vec!["--prefix".into()],
346 vec!["--repository".into()],
347 vec!["--cellar".into()],
348 vec![
349 "info".into(),
350 "--json=v2".into(),
351 "--formula".into(),
352 format!("homebrew/core/{package}"),
353 ],
354 ]
355}
356pub(super) fn environment(command: &mut Command) {
357 for key in CONTROLS {
358 command.env(key, "1");
359 }
360}
361fn command(executable: &Path, home: &Path, search_dirs: &[PathBuf], args: &[String]) -> Command {
362 let mut c = Command::new(executable);
363 c.env_clear()
364 .env("HOME", home)
365 .env("XDG_CONFIG_HOME", home.join(".config"))
366 .env("XDG_CACHE_HOME", home.join(".cache"))
367 .env("XDG_DATA_HOME", home.join(".local/share"))
368 .env("XDG_STATE_HOME", home.join(".local/state"))
369 .env(
370 "PATH",
371 std::env::join_paths(search_dirs).expect("validated scope"),
372 )
373 .env("LC_ALL", "C")
374 .env("LANG", "C")
375 .env("NO_COLOR", "1")
376 .current_dir("/")
377 .args(args);
378 environment(&mut c);
379 c
380}
381fn query(s: &super::Scope, args: &[String]) -> Result<Vec<u8>> {
382 inspection::run_bounded(
383 command(&s.executable, &s.home, &s.search_dirs, args),
384 4 * 1024 * 1024,
385 Duration::from_secs(10),
386 )
387 .map_err(|_| {
388 invalid("Homebrew probe unavailable, failed or exceeded bounds; raw output withheld")
389 })
390}
391pub(super) fn closure_prefix(
392 executable: &Path,
393 home: &Path,
394 search_dirs: &[PathBuf],
395 expected: &Path,
396) -> Result<()> {
397 let bytes = inspection::run_bounded(
398 command(executable, home, search_dirs, &["--prefix".into()]),
399 8192,
400 Duration::from_secs(10),
401 )
402 .map_err(|_| invalid("Homebrew closure prefix probe unavailable; contents withheld"))?;
403 if path(&bytes)? != expected {
404 return Err(invalid(
405 "Homebrew closure prefix differs from approved scope",
406 ));
407 }
408 Ok(())
409}
410fn path(bytes: &[u8]) -> Result<PathBuf> {
411 let text =
412 std::str::from_utf8(bytes).map_err(|_| invalid("invalid Homebrew layout metadata"))?;
413 let text = text.strip_suffix('\n').unwrap_or(text);
414 if text.len() > 4096 || text.bytes().any(|b| b < 32 || b == 127) {
415 return Err(invalid("invalid Homebrew layout metadata"));
416 }
417 let p = PathBuf::from(text);
418 if !inspection::absolute(&p) {
422 return Err(invalid("invalid Homebrew layout path"));
423 }
424 Ok(p)
425}
426pub(super) fn probe(s: &super::Scope, mut check: impl FnMut() -> Result<()>) -> Result<Probe> {
429 let b = s.brew.as_ref().expect("brew scope");
430 let args = probe_arguments(&s.package);
431 check()?;
432 let help = query(s, &args[0])?;
433 check()?;
434 let help = std::str::from_utf8(&help)
435 .map_err(|_| invalid("Homebrew install capabilities unavailable"))?;
436 for flag in [
437 "--formula",
438 "--no-ask",
439 "--skip-post-install",
440 "HOMEBREW_NO_INSTALL_UPGRADE",
441 "HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK",
442 "HOMEBREW_NO_INSTALL_CLEANUP",
443 ] {
444 if !help
445 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
446 .any(|word| word == flag)
447 {
448 return Err(invalid(
449 "Homebrew does not advertise all required install controls; no weaker fallback",
450 ));
451 }
452 }
453 for (args, expected) in args[1..4].iter().zip([&b.prefix, &b.repository, &b.cellar]) {
454 check()?;
455 let observed = path(&query(s, args)?)?;
456 check()?;
457 if &observed != expected {
458 return Err(invalid(
459 "Homebrew native layout differs from selected physical scope",
460 ));
461 }
462 }
463 check()?;
464 let (stable_version, installed_versions) = formula_info(s)?;
465 check()?;
466 Ok(Probe {
467 required_controls_advertised: true,
468 prefix: b.prefix.clone(),
469 repository: b.repository.clone(),
470 cellar: b.cellar.clone(),
471 stable_version,
472 installed_versions,
473 })
474}
475#[cfg(test)]
476mod tests {
477 #[test]
478 fn root_owned_prefix_never_grants_permission_to_native_write_roots() {
479 use super::writable_root;
480 let groups = [20];
481 assert!(writable_root(0, 0, 0o755, 501, &groups, true));
482 assert!(!writable_root(0, 0, 0o755, 501, &groups, false));
483 assert!(writable_root(501, 20, 0o755, 501, &groups, false));
484 for mode in [0o777, 0o500, 0o555] {
485 assert!(!writable_root(501, 20, mode, 501, &groups, false));
486 }
487 assert!(!writable_root(502, 20, 0o755, 501, &groups, false));
488 }
489 #[test]
490 fn group_write_is_accepted_only_for_the_callers_own_groups() {
491 use super::{safe_parent, writable_root};
492 let groups = [20, 80];
493 assert!(writable_root(501, 20, 0o775, 501, &groups, false));
494 assert!(writable_root(501, 80, 0o770, 501, &groups, true));
495 assert!(!writable_root(501, 99, 0o770, 501, &groups, false));
496 assert!(!writable_root(501, 20, 0o777, 501, &groups, false));
497 assert!(writable_root(0, 20, 0o775, 501, &groups, true));
498 assert!(!writable_root(0, 99, 0o775, 501, &groups, true));
499 assert!(!writable_root(0, 20, 0o775, 501, &groups, false));
500 assert!(writable_root(0, 20, 0o755, 501, &groups, true));
501 let parent = |uid, gid, mode| crate::observation::Fingerprint {
502 device: 0,
503 inode: 0,
504 links: 0,
505 mode,
506 uid,
507 gid,
508 size: 0,
509 modified: (0, 0),
510 changed: (0, 0),
511 };
512 assert!(safe_parent(&parent(501, 20, 0o775), 501, &groups));
513 assert!(!safe_parent(&parent(501, 99, 0o775), 501, &groups));
514 assert!(!safe_parent(&parent(501, 20, 0o777), 501, &groups));
515 assert!(safe_parent(&parent(0, 0, 0o755), 501, &groups));
516 assert!(!safe_parent(&parent(502, 20, 0o755), 501, &groups));
517 }
518}
519#[derive(Deserialize)]
520struct Info {
521 formulae: Vec<Formula>,
522}
523#[derive(Deserialize)]
524struct Formula {
525 name: String,
526 full_name: String,
527 tap: String,
528 disabled: bool,
529 #[serde(default)]
530 aliases: Vec<String>,
531 #[serde(default)]
532 oldnames: Vec<String>,
533 installed: Vec<Installed>,
534 versions: Versions,
535}
536#[derive(Deserialize)]
537struct Versions {
538 stable: Option<String>,
539 head: Option<String>,
540}
541#[derive(Deserialize)]
542struct Installed {
543 version: String,
544}
545pub(super) fn formula_info(s: &super::Scope) -> Result<(String, Vec<String>)> {
546 let bytes = query(s, &probe_arguments(&s.package)[4])?;
547 let mut info: Info = serde_json::from_slice(&bytes)
548 .map_err(|_| invalid("invalid Homebrew formula metadata; raw output withheld"))?;
549 if info.formulae.len() != 1 {
550 return Err(invalid("ambiguous Homebrew formula metadata"));
551 }
552 let f = info.formulae.remove(0);
553 if f.name != s.package
554 || (f.full_name != s.package && f.full_name != format!("homebrew/core/{}", s.package))
555 || f.tap != "homebrew/core"
556 || f.disabled
557 || !f.aliases.is_empty()
558 || !f.oldnames.is_empty()
559 || f.versions
560 .stable
561 .as_ref()
562 .is_none_or(|v| !super::super::valid_observed_version(v))
563 || f.installed.len() > 256
564 {
565 return Err(invalid(
566 "Homebrew target is not an available unambiguous canonical core formula",
567 ));
568 }
569 let mut versions = Vec::new();
572 for i in f.installed {
573 if !super::super::valid_observed_version(&i.version)
574 || i.version.starts_with("HEAD")
575 || f.versions.head.as_ref() == Some(&i.version)
576 {
577 return Err(invalid("unsupported Homebrew installed version metadata"));
578 }
579 versions.push(i.version);
580 }
581 versions.sort();
582 versions.dedup();
583 Ok((f.versions.stable.expect("validated stable"), versions))
584}