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 prepare_inner(host, request, brew, reports, false)
125}
126
127pub(crate) fn prepare_environment(
128 host: &HostContext,
129 request: Request,
130 brew: Scope,
131 reports: &[&inspection::Report],
132) -> Result<Preview> {
133 prepare_inner(host, request, brew, reports, true)
134}
135
136fn prepare_inner(
137 host: &HostContext,
138 request: Request,
139 brew: Scope,
140 reports: &[&inspection::Report],
141 environment: bool,
142) -> Result<Preview> {
143 let (manifest, scope, sources) = super::sources(host, &request, None, Some(&brew))?;
144 super::bounded_metadata(&scope, &sources)?;
145 catalogs(&scope, &brew, reports)?;
146 let row = super::evaluate_catalogs(host, &manifest, &scope, reports)?;
147 if !super::reviewable(&row, environment) {
148 return Err(invalid(
149 "only an observed missing canonical core formula with clear explicit prerequisites can be reviewed",
150 ));
151 }
152 Ok(Preview {
153 request,
154 scope,
155 sources,
156 })
157}
158pub(super) fn catalogs<'a>(
159 s: &super::Scope,
160 b: &Scope,
161 reports: &[&'a inspection::Report],
162) -> Result<BTreeMap<String, &'a inspection::Report>> {
163 if b.catalogs.len() != reports.len() {
164 return Err(invalid("Homebrew catalog count differs"));
165 }
166 let mut out = BTreeMap::new();
167 for (c, r) in b.catalogs.iter().zip(reports) {
168 if !c.matches(&s.home, r) {
169 return Err(invalid("Homebrew prerequisite catalog scope differs"));
170 }
171 for id in &c.tools {
172 if out.insert(id.clone(), *r).is_some() {
173 return Err(invalid("duplicate Homebrew catalog binding"));
174 }
175 }
176 }
177 Ok(out)
178}
179#[derive(Clone, Serialize, Deserialize)]
180#[serde(deny_unknown_fields)]
181pub(super) struct Sources {
182 bindings: npm::Sources,
183 parents: Vec<observation::Parent>,
184}
185pub(super) fn effect_sources(sources: &Sources) -> Sources {
186 Sources {
187 bindings: npm::effect_sources(&sources.bindings),
188 parents: sources.parents.clone(),
189 }
190}
191pub(super) fn same(a: &Sources, b: &Sources) -> bool {
192 npm::same(&a.bindings, &b.bindings)
193 && a.parents.len() == b.parents.len()
194 && a.parents.iter().zip(&b.parents).all(|(a, b)| {
195 a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
196 })
197}
198fn writable_root(
202 owner: u32,
203 group: u32,
204 mode: u32,
205 uid: u32,
206 groups: &[u32],
207 prefix: bool,
208) -> bool {
209 if mode & 0o002 != 0 || (mode & 0o020 != 0 && !groups.contains(&group)) {
210 return false;
211 }
212 (owner == uid || (prefix && owner == 0)) && mode & 0o200 != 0
213}
214fn safe_parent(fingerprint: &observation::Fingerprint, uid: u32, groups: &[u32]) -> bool {
215 if fingerprint.mode & 0o002 != 0
216 || (fingerprint.mode & 0o020 != 0 && !groups.contains(&fingerprint.gid))
217 {
218 return false;
219 }
220 fingerprint.uid == uid || fingerprint.uid == 0
221}
222fn caller_groups() -> Vec<u32> {
223 let mut groups: Vec<u32> = rustix::process::getgroups()
224 .unwrap_or_default()
225 .iter()
226 .map(|g| g.as_raw())
227 .collect();
228 groups.push(rustix::process::getegid().as_raw());
229 groups.sort_unstable();
230 groups.dedup();
231 groups
232}
233pub(super) fn sources(s: &super::Scope) -> Result<Sources> {
234 let b = s.brew.as_ref().expect("brew scope");
235 let mut programs = vec![npm::program(&s.executable, true)?];
236 for c in &b.catalogs {
237 programs.push(npm::program(&c.executable, true)?);
238 if let Some(n) = &c.npm_binding {
239 programs.push(npm::program(&n.npm_cli, false)?);
240 }
241 }
242 let mut paths = BTreeSet::from([
245 b.prefix.clone(),
246 b.repository.clone(),
247 b.repository.join("Library"),
248 ]);
249 for root in [
250 "Cellar",
251 "bin",
252 "etc",
253 "include",
254 "lib",
255 "opt",
256 "sbin",
257 "share",
258 "var",
259 "var/homebrew",
260 ] {
261 paths.insert(b.prefix.join(root));
262 }
263 let uid = rustix::process::geteuid().as_raw();
264 let groups = caller_groups();
265 let directories = paths.into_iter().map(|path| {
266 let e = observation::inspect(&path, false)?;
267 if e.kind != Kind::Directory {
268 return Err(scope_invalid(format!(
269 "Homebrew folder {path:?} is missing or is not a real folder."
270 )));
271 }
272 let Some(fingerprint) = e.fingerprint.as_ref() else {
273 return Err(scope_invalid(format!(
274 "Homebrew folder {path:?} cannot be verified."
275 )));
276 };
277 if fingerprint.mode & 0o002 != 0 {
278 return Err(scope_invalid(format!(
279 "Homebrew folder {path:?} is writable by everyone."
280 )));
281 }
282 if fingerprint.mode & 0o020 != 0 && !groups.contains(&fingerprint.gid) {
283 return Err(scope_invalid(format!(
284 "Homebrew folder {path:?} is writable by a group you are not in."
285 )));
286 }
287 if !writable_root(
288 fingerprint.uid,
289 fingerprint.gid,
290 fingerprint.mode,
291 uid,
292 &groups,
293 path == b.prefix,
294 ) {
295 return Err(scope_invalid(format!(
296 "Homebrew folder {path:?} must belong to you and be writable by you."
297 )));
298 }
299 if let Some(parent) = e.parents.iter().find(|p| {
300 (!b.prefix.starts_with(&s.home) || p.path.starts_with(&s.home))
303 && !safe_parent(&p.fingerprint, uid, &groups)
304 }) {
305 return Err(scope_invalid(format!(
306 "Homebrew parent folder {:?} is writable by users outside your account or belongs to another account.",
307 parent.path
308 )));
309 }
310 Ok(e)
311 }).collect::<Result<Vec<_>>>()?;
312 let mut lookup = BTreeSet::new();
313 lookup.extend(s.tool_search_dirs.iter().cloned());
314 lookup.extend(s.search_dirs.iter().cloned());
315 for c in &b.catalogs {
316 lookup.extend(c.search_dirs.iter().cloned());
317 }
318 let tool_directories = lookup
319 .iter()
320 .map(|p| {
321 let e = observation::inspect(p, false)?;
322 if e.kind != Kind::Directory {
323 return Err(invalid("tool search directory unavailable or unsafe"));
324 }
325 Ok(e)
326 })
327 .collect::<Result<Vec<_>>>()?;
328 let mut bindings = npm::Sources {
329 programs,
330 directories,
331 tool_directories,
332 };
333 let mut parents = BTreeMap::<PathBuf, observation::Parent>::new();
336 for e in bindings
337 .programs
338 .iter_mut()
339 .chain(&mut bindings.directories)
340 .chain(&mut bindings.tool_directories)
341 {
342 for p in std::mem::take(&mut e.parents) {
343 if let Some(old) = parents.get(&p.path) {
344 if !adoption::parent_identity(&old.fingerprint, &p.fingerprint) {
345 return Err(invalid("Homebrew parents changed while binding"));
346 }
347 } else {
348 parents.insert(p.path.clone(), p);
349 }
350 }
351 }
352 Ok(Sources {
353 bindings,
354 parents: parents.into_values().collect(),
355 })
356}
357pub(super) fn arguments(package: &str) -> Vec<String> {
358 [
359 "install".into(),
360 "--formula".into(),
361 "--no-ask".into(),
362 "--skip-post-install".into(),
363 format!("homebrew/core/{package}"),
364 ]
365 .into()
366}
367pub(super) fn probe_arguments(package: &str) -> Vec<Vec<String>> {
368 vec![
369 vec!["help".into(), "install".into()],
370 vec!["--prefix".into()],
371 vec!["--repository".into()],
372 vec!["--cellar".into()],
373 vec![
374 "info".into(),
375 "--json=v2".into(),
376 "--formula".into(),
377 format!("homebrew/core/{package}"),
378 ],
379 ]
380}
381pub(super) fn environment(command: &mut Command) {
382 for key in CONTROLS {
383 command.env(key, "1");
384 }
385}
386fn command(executable: &Path, home: &Path, search_dirs: &[PathBuf], args: &[String]) -> Command {
387 let mut c = Command::new(executable);
388 c.env_clear()
389 .env("HOME", home)
390 .env("XDG_CONFIG_HOME", home.join(".config"))
391 .env("XDG_CACHE_HOME", home.join(".cache"))
392 .env("XDG_DATA_HOME", home.join(".local/share"))
393 .env("XDG_STATE_HOME", home.join(".local/state"))
394 .env(
395 "PATH",
396 std::env::join_paths(search_dirs).expect("validated scope"),
397 )
398 .env("LC_ALL", "C")
399 .env("LANG", "C")
400 .env("NO_COLOR", "1")
401 .current_dir("/")
402 .args(args);
403 environment(&mut c);
404 c
405}
406fn query(s: &super::Scope, args: &[String]) -> Result<Vec<u8>> {
407 inspection::run_bounded(
408 command(&s.executable, &s.home, &s.search_dirs, args),
409 4 * 1024 * 1024,
410 Duration::from_secs(10),
411 )
412 .map_err(|_| {
413 invalid("Homebrew probe unavailable, failed or exceeded bounds; raw output withheld")
414 })
415}
416pub(super) fn closure_prefix(
417 executable: &Path,
418 home: &Path,
419 search_dirs: &[PathBuf],
420 expected: &Path,
421) -> Result<()> {
422 let bytes = inspection::run_bounded(
423 command(executable, home, search_dirs, &["--prefix".into()]),
424 8192,
425 Duration::from_secs(10),
426 )
427 .map_err(|_| invalid("Homebrew closure prefix probe unavailable; contents withheld"))?;
428 if path(&bytes)? != expected {
429 return Err(invalid(
430 "Homebrew closure prefix differs from approved scope",
431 ));
432 }
433 Ok(())
434}
435fn path(bytes: &[u8]) -> Result<PathBuf> {
436 let text =
437 std::str::from_utf8(bytes).map_err(|_| invalid("invalid Homebrew layout metadata"))?;
438 let text = text.strip_suffix('\n').unwrap_or(text);
439 if text.len() > 4096 || text.bytes().any(|b| b < 32 || b == 127) {
440 return Err(invalid("invalid Homebrew layout metadata"));
441 }
442 let p = PathBuf::from(text);
443 if !inspection::absolute(&p) {
447 return Err(invalid("invalid Homebrew layout path"));
448 }
449 Ok(p)
450}
451pub(super) fn probe(s: &super::Scope, mut check: impl FnMut() -> Result<()>) -> Result<Probe> {
454 let b = s.brew.as_ref().expect("brew scope");
455 let args = probe_arguments(&s.package);
456 check()?;
457 let help = query(s, &args[0])?;
458 check()?;
459 let help = std::str::from_utf8(&help)
460 .map_err(|_| invalid("Homebrew install capabilities unavailable"))?;
461 for flag in [
462 "--formula",
463 "--no-ask",
464 "--skip-post-install",
465 "HOMEBREW_NO_INSTALL_UPGRADE",
466 "HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK",
467 "HOMEBREW_NO_INSTALL_CLEANUP",
468 ] {
469 if !help
470 .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
471 .any(|word| word == flag)
472 {
473 return Err(invalid(
474 "Homebrew does not advertise all required install controls; no weaker fallback",
475 ));
476 }
477 }
478 for (args, expected) in args[1..4].iter().zip([&b.prefix, &b.repository, &b.cellar]) {
479 check()?;
480 let observed = path(&query(s, args)?)?;
481 check()?;
482 if &observed != expected {
483 return Err(invalid(
484 "Homebrew native layout differs from selected physical scope",
485 ));
486 }
487 }
488 check()?;
489 let (stable_version, installed_versions) = formula_info(s)?;
490 check()?;
491 Ok(Probe {
492 required_controls_advertised: true,
493 prefix: b.prefix.clone(),
494 repository: b.repository.clone(),
495 cellar: b.cellar.clone(),
496 stable_version,
497 installed_versions,
498 })
499}
500#[cfg(test)]
501mod tests {
502 #[test]
503 fn root_owned_prefix_never_grants_permission_to_native_write_roots() {
504 use super::writable_root;
505 let groups = [20];
506 assert!(writable_root(0, 0, 0o755, 501, &groups, true));
507 assert!(!writable_root(0, 0, 0o755, 501, &groups, false));
508 assert!(writable_root(501, 20, 0o755, 501, &groups, false));
509 for mode in [0o777, 0o500, 0o555] {
510 assert!(!writable_root(501, 20, mode, 501, &groups, false));
511 }
512 assert!(!writable_root(502, 20, 0o755, 501, &groups, false));
513 }
514 #[test]
515 fn group_write_is_accepted_only_for_the_callers_own_groups() {
516 use super::{safe_parent, writable_root};
517 let groups = [20, 80];
518 assert!(writable_root(501, 20, 0o775, 501, &groups, false));
519 assert!(writable_root(501, 80, 0o770, 501, &groups, true));
520 assert!(!writable_root(501, 99, 0o770, 501, &groups, false));
521 assert!(!writable_root(501, 20, 0o777, 501, &groups, false));
522 assert!(writable_root(0, 20, 0o775, 501, &groups, true));
523 assert!(!writable_root(0, 99, 0o775, 501, &groups, true));
524 assert!(!writable_root(0, 20, 0o775, 501, &groups, false));
525 assert!(writable_root(0, 20, 0o755, 501, &groups, true));
526 let parent = |uid, gid, mode| crate::observation::Fingerprint {
527 device: 0,
528 inode: 0,
529 links: 0,
530 mode,
531 uid,
532 gid,
533 size: 0,
534 modified: (0, 0),
535 changed: (0, 0),
536 };
537 assert!(safe_parent(&parent(501, 20, 0o775), 501, &groups));
538 assert!(!safe_parent(&parent(501, 99, 0o775), 501, &groups));
539 assert!(!safe_parent(&parent(501, 20, 0o777), 501, &groups));
540 assert!(safe_parent(&parent(0, 0, 0o755), 501, &groups));
541 assert!(!safe_parent(&parent(502, 20, 0o755), 501, &groups));
542 }
543}
544#[derive(Deserialize)]
545struct Info {
546 formulae: Vec<Formula>,
547}
548#[derive(Deserialize)]
549struct Formula {
550 name: String,
551 full_name: String,
552 tap: String,
553 disabled: bool,
554 #[serde(default)]
555 aliases: Vec<String>,
556 #[serde(default)]
557 oldnames: Vec<String>,
558 installed: Vec<Installed>,
559 versions: Versions,
560}
561#[derive(Deserialize)]
562struct Versions {
563 stable: Option<String>,
564 head: Option<String>,
565}
566#[derive(Deserialize)]
567struct Installed {
568 version: String,
569}
570pub(super) fn formula_info(s: &super::Scope) -> Result<(String, Vec<String>)> {
571 let bytes = query(s, &probe_arguments(&s.package)[4])?;
572 let mut info: Info = serde_json::from_slice(&bytes)
573 .map_err(|_| invalid("invalid Homebrew formula metadata; raw output withheld"))?;
574 if info.formulae.len() != 1 {
575 return Err(invalid("ambiguous Homebrew formula metadata"));
576 }
577 let f = info.formulae.remove(0);
578 if f.name != s.package
579 || (f.full_name != s.package && f.full_name != format!("homebrew/core/{}", s.package))
580 || f.tap != "homebrew/core"
581 || f.disabled
582 || !f.aliases.is_empty()
583 || !f.oldnames.is_empty()
584 || f.versions
585 .stable
586 .as_ref()
587 .is_none_or(|v| !super::super::valid_observed_version(v))
588 || f.installed.len() > 256
589 {
590 return Err(invalid(
591 "Homebrew target is not an available unambiguous canonical core formula",
592 ));
593 }
594 let mut versions = Vec::new();
597 for i in f.installed {
598 if !super::super::valid_observed_version(&i.version)
599 || i.version.starts_with("HEAD")
600 || f.versions.head.as_ref() == Some(&i.version)
601 {
602 return Err(invalid("unsupported Homebrew installed version metadata"));
603 }
604 versions.push(i.version);
605 }
606 versions.sort();
607 versions.dedup();
608 Ok((f.versions.stable.expect("validated stable"), versions))
609}