Skip to main content

mur_common/
keychain_acl.rs

1//! Adding an app to a macOS Keychain item's "always allow" list (#2369).
2//!
3//! An item only trusts the binary that created it. Any other binary that
4//! reads it gets a modal "allow access" prompt. The agent runtime reads the
5//! browser state key unattended, just before its sandbox seals, so a prompt
6//! there blocks until the read times out. This module adds the runtime to the
7//! item's trusted-application list up front, the same way `-T /usr/bin/codesign`
8//! pre-authorises codesign for the self-signed certificate
9//! (`mur-core` `doctor_codesign`).
10//!
11//! Only the legacy `SecAccess` / `SecACL` calls can edit that list. Apple marks
12//! them deprecated, but they are still the only API for file-based keychains
13//! (`login.keychain-db`), and `security-framework` does not wrap them.
14//!
15//! [`check`] never prompts: it reads the item's access record, not its secret.
16//! [`ensure`] changes the access record, which macOS guards with the login
17//! keychain password. Call it only from a command a person is running.
18
19use std::path::Path;
20
21/// Whether an item's decrypt ACL already lets an app read it without a prompt.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Trust {
24    /// The app is listed, or the ACL has no app list (any app may read).
25    Trusted,
26    /// The app is not listed, so a read raises a prompt.
27    Missing,
28}
29
30#[derive(Debug, thiserror::Error)]
31pub enum AclError {
32    #[error("keychain item {service}/{account} does not exist")]
33    NotFound { service: String, account: String },
34    #[error("{call} failed (OSStatus {status})")]
35    Os { call: &'static str, status: i32 },
36    #[error("keychain item has no app list to add to")]
37    NoAppList,
38    #[error("keychain ACLs are only managed on macOS")]
39    Unsupported,
40}
41
42/// What [`check`] decides from the decrypt ACLs it found. `None` is an ACL with
43/// no app list; `Some` holds each listed app's identifying bytes.
44///
45/// This is a path-based approximation: the bytes are what
46/// `SecTrustedApplicationCopyData` returns, which is the app's path. macOS
47/// itself may match a signed app by its code requirement instead, so the two
48/// can disagree. An ad-hoc-signed build rebuilt at the same path can read as
49/// `Trusted` while the prompt returns; a Developer ID build at a new,
50/// versioned path (Homebrew, after `canonicalize`) can read as `Missing`
51/// while macOS still trusts it. Not yet verified on a real keychain.
52#[cfg(any(target_os = "macos", test))]
53fn decide(acls: &[Option<Vec<Vec<u8>>>], target: &[u8]) -> Trust {
54    let target = trim_nul(target);
55    let listed = acls.iter().any(|acl| match acl {
56        None => true,
57        Some(apps) => apps.iter().any(|a| trim_nul(a) == target),
58    });
59    if listed {
60        Trust::Trusted
61    } else {
62        Trust::Missing
63    }
64}
65
66/// `SecTrustedApplicationCopyData` returns a C path, sometimes with its NUL.
67#[cfg(any(target_os = "macos", test))]
68fn trim_nul(b: &[u8]) -> &[u8] {
69    let end = b.iter().rposition(|&c| c != 0).map_or(0, |i| i + 1);
70    &b[..end]
71}
72
73/// Whether `app` can read the generic password `service`/`account` without a
74/// prompt. Never prompts.
75pub fn check(service: &str, account: &str, app: &Path) -> Result<Trust, AclError> {
76    if crate::secret::keychain_blocked() {
77        return Err(AclError::Unsupported);
78    }
79    imp::check(service, account, app)
80}
81
82/// Add `app` to the item's decrypt ACL. Returns `true` when the ACL changed,
83/// `false` when `app` was already trusted. macOS asks for the login keychain
84/// password the first time; run it only where a person can answer.
85pub fn ensure(service: &str, account: &str, app: &Path) -> Result<bool, AclError> {
86    if crate::secret::keychain_blocked() {
87        return Err(AclError::Unsupported);
88    }
89    imp::ensure(service, account, app)
90}
91
92#[cfg(not(target_os = "macos"))]
93mod imp {
94    use super::*;
95    pub(super) fn check(_: &str, _: &str, _: &Path) -> Result<Trust, AclError> {
96        Err(AclError::Unsupported)
97    }
98    pub(super) fn ensure(_: &str, _: &str, _: &Path) -> Result<bool, AclError> {
99        Err(AclError::Unsupported)
100    }
101}
102
103#[cfg(target_os = "macos")]
104#[path = "keychain_acl_macos.rs"]
105mod imp;
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    fn apps(list: &[&str]) -> Option<Vec<Vec<u8>>> {
112        Some(list.iter().map(|s| s.as_bytes().to_vec()).collect())
113    }
114
115    #[test]
116    fn a_listed_app_is_trusted_with_or_without_the_nul() {
117        let acls = [apps(&["/bin/mur\0", "/usr/bin/security"])];
118        assert_eq!(decide(&acls, b"/bin/mur"), Trust::Trusted);
119        assert_eq!(decide(&acls, b"/bin/mur\0"), Trust::Trusted);
120    }
121
122    #[test]
123    fn an_unlisted_app_is_missing() {
124        let acls = [apps(&["/bin/mur"])];
125        assert_eq!(decide(&acls, b"/bin/mur-agent-runtime"), Trust::Missing);
126        assert_eq!(decide(&[], b"/bin/mur"), Trust::Missing);
127    }
128
129    #[test]
130    fn an_acl_without_an_app_list_lets_anyone_read() {
131        assert_eq!(decide(&[apps(&["/x"]), None], b"/y"), Trust::Trusted);
132    }
133
134    #[test]
135    fn trim_only_drops_trailing_nuls() {
136        assert_eq!(trim_nul(b"a\0b\0\0"), b"a\0b");
137        assert_eq!(trim_nul(b"\0"), b"");
138    }
139
140    #[test]
141    fn blocked_keychain_never_touches_the_os() {
142        // nextest sets NEXTEST, which blocks the keychain.
143        if crate::secret::keychain_blocked() {
144            assert!(matches!(
145                check("s", "a", Path::new("/x")),
146                Err(AclError::Unsupported)
147            ));
148            assert!(matches!(
149                ensure("s", "a", Path::new("/x")),
150                Err(AclError::Unsupported)
151            ));
152        }
153    }
154}