1#![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
24pub const DEFAULT_PAM_SERVICE: &str = "coqui-access";
26pub const DEFAULT_MIN_UID: u32 = os::FIRST_PERSON_UID;
29pub const DEFAULT_DOMAIN: &str = ".";
32pub const SUPPORTED: bool = os::SUPPORTED;
34
35#[derive(Debug, Clone, PartialEq, Eq, Describe)]
37#[map(deny_unknown_fields)]
38#[non_exhaustive]
39pub struct SystemAccountsConfig {
40 #[map(default = String::from(DEFAULT_PAM_SERVICE))]
43 pub pam_service: String,
44 #[map(default = DEFAULT_MIN_UID)]
46 pub min_uid: u32,
47 #[map(default)]
49 pub groups: Vec<String>,
50 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum NonDefault {
71 AdmitsRoot,
73 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 pub fn non_defaults(&self) -> Vec<NonDefault> {
90 #[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 #[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#[derive(Debug, Clone, Default)]
131#[must_use]
132pub struct SystemAccountsBuilder {
133 config: SystemAccountsConfig,
134}
135
136impl SystemAccountsBuilder {
137 pub fn pam_service(mut self, service: impl Into<String>) -> Self {
139 self.config.pam_service = service.into();
140 self
141 }
142
143 pub fn min_uid(mut self, uid: u32) -> Self {
145 self.config.min_uid = uid;
146 self
147 }
148
149 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 pub fn domain(mut self, domain: impl Into<String>) -> Self {
157 self.config.domain = domain.into();
158 self
159 }
160
161 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#[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 pub fn builder() -> SystemAccountsBuilder {
201 SystemAccountsBuilder::default()
202 }
203
204 pub fn new(config: SystemAccountsConfig) -> Result<Self, ProviderError> {
210 SystemAccountsBuilder { config }.build()
211 }
212
213 pub fn config(&self) -> &SystemAccountsConfig {
215 &self.config
216 }
217
218 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 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 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 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;