Skip to main content

coqui_access_system/
lib.rs

1//! The operating system's own accounts as an authenticator and a directory.
2#![doc = include_str!("../README.md")]
3#![deny(unsafe_code)]
4#![warn(missing_debug_implementations)]
5#![warn(missing_docs)]
6#![warn(
7    clippy::std_instead_of_core,
8    clippy::std_instead_of_alloc,
9    clippy::alloc_instead_of_core
10)]
11
12mod os;
13
14use core::fmt;
15
16use coqui_access::guatiao::library::ProviderError;
17use coqui_access::guatiao::{Provider, ToValue};
18use coqui_access::{
19    Attempt, Authenticator, Description, Directory, Lookup, Person, Verdict, error, takes,
20};
21use coqui_builder::Describe;
22use guatiao_builder::Described;
23
24/// The PAM service checked unless the configuration names another.
25pub const DEFAULT_PAM_SERVICE: &str = "coqui-access";
26/// The lowest uid admitted unless the configuration says otherwise: the first uid this
27/// platform gives a person (Linux 1000, FreeBSD 1001, macOS 501; 0 elsewhere).
28pub const DEFAULT_MIN_UID: u32 = os::FIRST_PERSON_UID;
29/// The Windows domain an account belongs to unless the configuration names another: `.`,
30/// the machine's own accounts.
31pub const DEFAULT_DOMAIN: &str = ".";
32/// Whether this build can reach the operating system's accounts: Unix and Windows.
33pub const SUPPORTED: bool = os::SUPPORTED;
34
35/// Options of [`SystemAccounts`], as a host's configuration holds them. Every key is optional.
36#[derive(Debug, Clone, PartialEq, Eq, Describe)]
37#[map(deny_unknown_fields)]
38#[non_exhaustive]
39pub struct SystemAccountsConfig {
40    /// The PAM service a password is checked under (Unix). With no file of that name in
41    /// `/etc/pam.d`, Linux-PAM uses `other`, which refuses everyone on most distributions.
42    #[map(default = String::from(DEFAULT_PAM_SERVICE))]
43    pub pam_service: String,
44    /// The lowest uid admitted (Unix). `0` admits root.
45    #[map(default = DEFAULT_MIN_UID)]
46    pub min_uid: u32,
47    /// The groups an account must belong to one of; empty admits any.
48    #[map(default)]
49    pub groups: Vec<String>,
50    /// The Windows domain accounts belong to; `.` is the machine's own accounts.
51    #[map(default = String::from(DEFAULT_DOMAIN))]
52    pub domain: String,
53}
54
55impl Default for SystemAccountsConfig {
56    fn default() -> Self {
57        Self {
58            pam_service: DEFAULT_PAM_SERVICE.to_owned(),
59            min_uid: DEFAULT_MIN_UID,
60            groups: Vec::new(),
61            domain: DEFAULT_DOMAIN.to_owned(),
62        }
63    }
64}
65
66/// A setting that admits more than the defaults do. Reported, never refused: the host
67/// decides what to do about it.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum NonDefault {
71    /// `min_uid` is 0 on Unix: root can sign in.
72    AdmitsRoot,
73    /// `min_uid` is below [`DEFAULT_MIN_UID`] but not 0 on Unix: service accounts can sign in.
74    AdmitsServiceAccounts,
75}
76
77impl fmt::Display for NonDefault {
78    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79        formatter.write_str(match self {
80            Self::AdmitsRoot => "min_uid 0 admits root",
81            Self::AdmitsServiceAccounts => "min_uid admits service accounts",
82        })
83    }
84}
85
86impl SystemAccountsConfig {
87    /// What these options admit beyond the defaults, on this platform. Empty with the
88    /// defaults.
89    pub fn non_defaults(&self) -> Vec<NonDefault> {
90        // Windows accounts carry no uid, so `min_uid` admits nothing there.
91        #[cfg(unix)]
92        match self.min_uid {
93            0 => vec![NonDefault::AdmitsRoot],
94            uid if uid < DEFAULT_MIN_UID => vec![NonDefault::AdmitsServiceAccounts],
95            _ => Vec::new(),
96        }
97        #[cfg(not(unix))]
98        Vec::new()
99    }
100
101    fn check(&self) -> Result<(), ProviderError> {
102        let plain = |text: &str| !text.is_empty() && !text.chars().any(char::is_control);
103        // Windows accounts carry no uid: a threshold there would silently admit everyone.
104        #[cfg(not(unix))]
105        if self.min_uid != DEFAULT_MIN_UID {
106            return Err(error::bad_value(
107                "min_uid has no meaning here: Windows accounts carry no uid",
108            ));
109        }
110        if !plain(&self.pam_service) || self.pam_service.contains('/') {
111            return Err(error::bad_value(
112                "pam_service must be a service name: not empty, no '/' and no control characters",
113            ));
114        }
115        if !plain(&self.domain) {
116            return Err(error::bad_value(
117                "domain must not be empty or hold control characters",
118            ));
119        }
120        if !self.groups.iter().all(|group| plain(group)) {
121            return Err(error::bad_value(
122                "a group must not be empty or hold control characters",
123            ));
124        }
125        Ok(())
126    }
127}
128
129/// Options for [`SystemAccounts`]; every one has a default.
130#[derive(Debug, Clone, Default)]
131#[must_use]
132pub struct SystemAccountsBuilder {
133    config: SystemAccountsConfig,
134}
135
136impl SystemAccountsBuilder {
137    /// The PAM service passwords are checked under. Default [`DEFAULT_PAM_SERVICE`].
138    pub fn pam_service(mut self, service: impl Into<String>) -> Self {
139        self.config.pam_service = service.into();
140        self
141    }
142
143    /// The lowest uid admitted. Default [`DEFAULT_MIN_UID`]; `0` admits root.
144    pub fn min_uid(mut self, uid: u32) -> Self {
145        self.config.min_uid = uid;
146        self
147    }
148
149    /// The groups an account must belong to one of. Default: none, which admits any.
150    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
151        self.config.groups = groups.into_iter().map(Into::into).collect();
152        self
153    }
154
155    /// The Windows domain accounts belong to. Default [`DEFAULT_DOMAIN`].
156    pub fn domain(mut self, domain: impl Into<String>) -> Self {
157        self.config.domain = domain.into();
158        self
159    }
160
161    /// Makes the provider. Nothing is looked up yet.
162    ///
163    /// # Errors
164    ///
165    /// Unsupported on a platform with no implementation ([`SUPPORTED`] is false); a bad
166    /// value for an empty or malformed service, domain or group.
167    pub fn build(self) -> Result<SystemAccounts, ProviderError> {
168        if !SUPPORTED {
169            return Err(error::unsupported(
170                "this platform's accounts are not supported",
171            ));
172        }
173        self.config.check()?;
174        Ok(SystemAccounts {
175            config: self.config,
176        })
177    }
178}
179
180/// The operating system's accounts: who may sign in is who the OS lets sign in, narrowed by
181/// [`SystemAccountsConfig::min_uid`] and [`SystemAccountsConfig::groups`].
182///
183/// Read only: accounts are managed with the OS's own tools. Every call blocks on the OS
184/// (PAM may sleep seconds after a wrong password), so a host calls it from a blocking thread.
185#[derive(Debug, Provider)]
186#[provider(
187    Authenticator,
188    Directory,
189    id = "coqui_access_system",
190    name = "System accounts",
191    config = Described<SystemAccountsConfig>,
192    crate = ::coqui_access::guatiao
193)]
194pub struct SystemAccounts {
195    config: SystemAccountsConfig,
196}
197
198impl SystemAccounts {
199    /// Options for the OS's accounts, each at its default.
200    pub fn builder() -> SystemAccountsBuilder {
201        SystemAccountsBuilder::default()
202    }
203
204    /// The provider these options describe.
205    ///
206    /// # Errors
207    ///
208    /// As [`SystemAccountsBuilder::build`].
209    pub fn new(config: SystemAccountsConfig) -> Result<Self, ProviderError> {
210        SystemAccountsBuilder { config }.build()
211    }
212
213    /// The options in force.
214    pub fn config(&self) -> &SystemAccountsConfig {
215        &self.config
216    }
217
218    /// The account `lookup` names, when the OS has it and these options admit it.
219    fn admitted(&self, lookup: &Lookup) -> Result<Option<os::Account>, ProviderError> {
220        if lookup.value.is_empty() || lookup.value.contains('\0') {
221            return Ok(None);
222        }
223        let found = match lookup.by.as_str() {
224            "id" => os::by_id(&lookup.value, &self.config)?,
225            "name" => os::by_name(&lookup.value, &self.config)?,
226            _ => None,
227        };
228        Ok(found.filter(|account| account.admitted_by(&self.config)))
229    }
230}
231
232impl TryFrom<Described<SystemAccountsConfig>> for SystemAccounts {
233    type Error = ProviderError;
234
235    fn try_from(config: Described<SystemAccountsConfig>) -> Result<Self, Self::Error> {
236        Self::new(config.0)
237    }
238}
239
240impl TryFrom<SystemAccountsConfig> for SystemAccounts {
241    type Error = ProviderError;
242
243    fn try_from(config: SystemAccountsConfig) -> Result<Self, Self::Error> {
244        Self::new(config)
245    }
246}
247
248impl os::Account {
249    fn admitted_by(&self, config: &SystemAccountsConfig) -> bool {
250        self.uid.is_none_or(|uid| uid >= config.min_uid)
251            && (config.groups.is_empty()
252                || self
253                    .groups
254                    .iter()
255                    .any(|group| config.groups.iter().any(|allowed| allowed == group)))
256    }
257
258    /// The person, with `uid` and `home` as attributes where the OS has them: what a
259    /// per-user pin file is found and trusted by.
260    fn person(self) -> Person {
261        let mut attributes = Person::default().attributes;
262        if let Some(uid) = self.uid
263            && let Ok(value) = uid.to_string().to_value()
264        {
265            attributes.insert("uid".to_owned(), value);
266        }
267        if let Some(home) = &self.home
268            && let Ok(value) = home.to_value()
269        {
270            attributes.insert("home".to_owned(), value);
271        }
272        Person {
273            id: self.id,
274            name: self.name,
275            display_name: self.display_name,
276            email: None,
277            groups: self.groups,
278            attributes,
279        }
280    }
281}
282
283impl Authenticator for SystemAccounts {
284    /// A name the OS does not have, or these options do not admit, is `Unknown`; a wrong
285    /// password, or a disabled, locked or expired account, is `Invalid`; success names the
286    /// account `by: "id"` (the uid, or the SID on Windows).
287    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
288        let (Some(name), Some(password)) = (attempt.name, attempt.secret) else {
289            return Ok(Verdict::Unknown);
290        };
291        let lookup = Lookup {
292            by: "name".to_owned(),
293            value: name,
294            ..Lookup::default()
295        };
296        let Some(account) = self.admitted(&lookup)? else {
297            return Ok(Verdict::Unknown);
298        };
299        if account.disabled || password.is_empty() || password.contains('\0') {
300            return Ok(Verdict::Invalid);
301        }
302        Ok(
303            if os::check_password(&account.name, &password, &self.config)? {
304                Verdict::Valid(Lookup {
305                    by: "id".to_owned(),
306                    value: account.id,
307                    ..Lookup::default()
308                })
309            } else {
310                Verdict::Invalid
311            },
312        )
313    }
314
315    fn describe(&self) -> Result<Description, ProviderError> {
316        Ok(Description {
317            name: Some("System accounts".to_owned()),
318            takes: Some(takes::PASSWORD.to_owned()),
319        })
320    }
321}
322
323impl Directory for SystemAccounts {
324    /// By `id` (uid, or SID on Windows) or `name`; a disabled or unadmitted account is
325    /// `None`.
326    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
327        Ok(self
328            .admitted(&lookup)?
329            .filter(|account| !account.disabled)
330            .map(os::Account::person))
331    }
332
333    fn describe(&self) -> Result<Description, ProviderError> {
334        Ok(Description {
335            name: Some("System accounts".to_owned()),
336            takes: None,
337        })
338    }
339}
340
341#[cfg(test)]
342mod tests;