1#[cfg(test)]
4mod tests;
5
6use std::cell::{Cell, RefCell};
7use std::ffi::{OsStr, OsString};
8use std::os::unix::ffi::OsStrExt;
9use std::rc::Rc;
10use std::sync::{Arc, Once, mpsc};
11
12use calloop::RegistrationToken;
13use calloop::channel::Event as Arrived;
14use crabshell_reactive::{ReadSignal, Signal, untrack};
15use crabshell_ui::Cx;
16use nonstick::{AuthnFlags, ConversationAdapter, ErrorCode, Transaction, TransactionBuilder};
17
18use crate::Shared;
19
20const MAX_TEXT: usize = 4096;
22
23pub(crate) const MAX_MESSAGES: usize = 64;
25
26pub(crate) struct Service(pub(crate) Rc<Shared>);
28
29#[derive(Clone, Debug, PartialEq)]
31pub enum PamState {
32 Idle,
34 Asking {
37 message: String,
39 visible: bool,
42 },
43 Busy,
45 Done(PamResult),
47}
48
49#[derive(Clone, Debug, PartialEq)]
51pub enum PamResult {
52 Success,
54 Failure,
56 Error {
58 kind: PamError,
60 message: String,
62 },
63}
64
65impl PamResult {
66 pub(crate) fn error(kind: PamError, message: impl Into<String>) -> PamResult {
67 let message = message.into();
68 PamResult::Error { kind, message }
69 }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum PamError {
75 StartFailed,
78 TryAuthFailed,
84 InternalError,
87}
88
89#[derive(Clone, Debug, PartialEq)]
92pub enum PamMessage {
93 Info(String),
95 Error(String),
97}
98
99#[derive(Clone)]
107pub struct Pam {
108 inner: Rc<Inner>,
109}
110
111struct Inner {
112 shared: Option<Rc<Shared>>,
114 service: String,
115 state: Signal<PamState>,
117 messages: Signal<Vec<PamMessage>>,
118 attempt: RefCell<Option<Attempt>>,
119 abandoned: RefCell<Option<RegistrationToken>>,
122 waiting: RefCell<Option<Option<String>>>,
125 next: Cell<u64>,
127}
128
129struct Attempt {
131 number: u64,
134 source: RegistrationToken,
136 answers: mpsc::Sender<Secret>,
139 asking: bool,
141}
142
143pub(crate) enum Event {
145 Ask { message: String, visible: bool },
146 Tell(PamMessage),
147 Done(PamResult),
148}
149
150pub(crate) trait Backend: Send + Sync {
152 fn authenticate(&self, service: &str, user: &str, talk: &Talk) -> PamResult;
155}
156
157pub(crate) struct Talk {
159 events: calloop::channel::Sender<Event>,
160 answers: mpsc::Receiver<Secret>,
161}
162
163impl Talk {
164 pub(crate) fn ask(&self, question: &OsStr, visible: bool) -> Option<Secret> {
168 let message = cut(question);
169 self.events.send(Event::Ask { message, visible }).ok()?;
170 self.answers.recv().ok()
171 }
172
173 pub(crate) fn tell(&self, kind: fn(String) -> PamMessage, text: &OsStr) {
175 let _ = self.events.send(Event::Tell(kind(cut(text))));
177 }
178}
179
180fn cut(text: &OsStr) -> String {
183 let mut text = text.to_string_lossy().into_owned();
184 text.truncate(text.floor_char_boundary(MAX_TEXT));
185 text
186}
187
188pub(crate) struct Secret(Vec<u8>);
191
192impl Secret {
193 pub(crate) fn bytes(&self) -> &[u8] {
194 &self.0
195 }
196}
197
198impl Drop for Secret {
199 fn drop(&mut self) {
200 wipe(&mut self.0);
201 }
202}
203
204pub(crate) fn wipe(bytes: &mut Vec<u8>) {
206 bytes.clear();
207 bytes.resize(bytes.capacity(), 0);
208 std::hint::black_box(bytes);
210}
211
212pub(crate) fn pam(cx: &Cx, service: &str) -> Pam {
214 let shared = cx.service::<Service>().map(|service| Rc::clone(&service.0));
215 if shared.is_none() {
216 static LOGGED: Once = Once::new();
217 LOGGED.call_once(|| {
218 tracing::warn!("cx.pam() needs the services the shell provides; it never authenticates");
219 });
220 }
221 let inner = Rc::new(Inner {
222 shared,
223 service: service.to_owned(),
224 state: cx.signal(PamState::Idle),
225 messages: cx.signal(Vec::new()),
226 attempt: RefCell::default(),
227 abandoned: RefCell::default(),
228 waiting: RefCell::default(),
229 next: Cell::new(0),
230 });
231 cx.owner().signal(EndOnDrop(Rc::clone(&inner)));
233 Pam { inner }
234}
235
236struct EndOnDrop(Rc<Inner>);
238
239impl Drop for EndOnDrop {
240 fn drop(&mut self) {
241 self.0.end();
242 self.0.waiting.take();
243 if let Some(token) = self.0.abandoned.take() {
244 self.0.remove(token);
245 }
246 }
247}
248
249impl Pam {
250 pub fn start(&self, user: Option<&str>) {
265 self.inner.abort();
266 self.inner.start(user.map(str::to_owned));
267 }
268
269 pub fn respond(&self, text: impl Into<String>) {
275 self.inner.respond(Secret(text.into().into_bytes()));
276 }
277
278 pub fn abort(&self) {
285 self.inner.abort();
286 }
287
288 pub fn state(&self) -> ReadSignal<PamState> {
290 self.inner.state.read_only()
291 }
292
293 pub fn messages(&self) -> ReadSignal<Vec<PamMessage>> {
296 self.inner.messages.read_only()
297 }
298}
299
300impl Inner {
301 fn alive(&self) -> bool {
304 untrack(|| self.state.try_with(|_| ()).is_some())
305 }
306
307 fn start(self: &Rc<Self>, user: Option<String>) {
308 let Some(shared) = &self.shared else {
309 return;
310 };
311 let Some(event_loop) = shared.event_loop() else {
312 return;
313 };
314 if !self.alive() {
315 return;
316 }
317 if self.abandoned.borrow().is_some() {
318 *self.waiting.borrow_mut() = Some(user);
319 set(self.messages, Vec::new());
320 return set(self.state, PamState::Busy);
321 }
322 let (events, channel) = calloop::channel::channel();
323 let (answers, inbox) = mpsc::channel();
324 let inner = Rc::clone(self);
325 let number = self.next.replace(self.next.get() + 1);
326 let arrived = Box::new(move |event| inner.arrived(number, event));
327 let Some(source) = event_loop.insert_pam_channel(channel, arrived) else {
328 return;
329 };
330 let backend = Arc::clone(&shared.config.pam);
331 let service = self.service.clone();
332 let talk = Talk {
333 events,
334 answers: inbox,
335 };
336 let spawned = std::thread::Builder::new()
337 .name(String::from("crabshell-pam"))
338 .spawn(move || {
339 let result = match user.map_or_else(own_user, Ok) {
340 Ok(user) => backend.authenticate(&service, &user, &talk),
341 Err(error) => PamResult::error(PamError::StartFailed, error),
342 };
343 let _ = talk.events.send(Event::Done(result));
345 });
346 if let Err(error) = spawned {
347 tracing::error!(%error, "PAM couldn't start a thread");
349 }
350 *self.attempt.borrow_mut() = Some(Attempt {
351 number,
352 source,
353 answers,
354 asking: false,
355 });
356 set(self.messages, Vec::new());
357 set(self.state, PamState::Busy);
358 }
359
360 fn arrived(self: &Rc<Self>, number: u64, event: Arrived<Event>) {
361 let live = self.attempt.borrow().as_ref().map(|attempt| attempt.number);
362 if live != Some(number) {
363 if let Arrived::Closed = event {
365 self.returned();
366 }
367 return;
368 }
369 match event {
370 Arrived::Msg(Event::Ask { message, visible }) => {
371 if let Some(attempt) = self.attempt.borrow_mut().as_mut() {
372 attempt.asking = true;
373 }
374 set(self.state, PamState::Asking { message, visible });
375 }
376 Arrived::Msg(Event::Tell(message)) => {
377 self.messages.try_update(|messages| {
378 if messages.len() == MAX_MESSAGES {
379 messages.remove(0);
380 }
381 messages.push(message);
382 });
383 }
384 Arrived::Msg(Event::Done(result)) => self.finish(result),
385 Arrived::Closed => self.finish(PamResult::error(
387 PamError::InternalError,
388 "the attempt ended without a result",
389 )),
390 }
391 }
392
393 fn respond(&self, secret: Secret) {
394 {
395 let mut attempt = self.attempt.borrow_mut();
396 let Some(attempt) = attempt.as_mut().filter(|attempt| attempt.asking) else {
397 return tracing::warn!("PAM asked no question, so a response was dropped");
399 };
400 attempt.asking = false;
401 let _ = attempt.answers.send(secret);
403 }
404 set(self.state, PamState::Busy);
405 }
406
407 fn finish(&self, result: PamResult) {
408 if self.end() {
409 set(self.state, PamState::Done(result));
410 }
411 }
412
413 fn abort(&self) {
417 let waited = self.waiting.take().is_some();
418 let attempt = self.attempt.borrow_mut().take();
419 if let Some(attempt) = &attempt {
420 *self.abandoned.borrow_mut() = Some(attempt.source);
421 }
422 if waited || attempt.is_some() {
423 set(self.state, PamState::Idle);
424 }
425 }
426
427 fn returned(self: &Rc<Self>) {
430 if let Some(token) = self.abandoned.take() {
431 self.remove(token);
432 }
433 let waiting = self.waiting.take();
434 if let Some(user) = waiting {
435 self.start(user);
436 }
437 }
438
439 fn end(&self) -> bool {
443 let Some(attempt) = self.attempt.borrow_mut().take() else {
444 return false;
445 };
446 self.remove(attempt.source);
447 true
448 }
449
450 fn remove(&self, token: RegistrationToken) {
451 if let Some(event_loop) = self.shared.as_ref().and_then(|shared| shared.event_loop()) {
452 event_loop.remove(token);
453 }
454 }
455}
456
457fn own_user() -> Result<String, String> {
460 let uid = rustix::process::getuid().as_raw();
461 crate::user_name(uid).ok_or_else(|| format!("no user with uid {uid}"))
462}
463
464pub(crate) struct LibPam;
466
467impl Backend for LibPam {
468 fn authenticate(&self, service: &str, user: &str, talk: &Talk) -> PamResult {
469 if service.contains('\0') || user.contains('\0') {
471 return PamResult::error(PamError::StartFailed, "a service or user name with a NUL");
472 }
473 let built = TransactionBuilder::new_with_service(service)
474 .username(user)
475 .build(Adapter(talk).into_conversation());
476 let mut transaction = match built {
477 Ok(transaction) => transaction,
478 Err(error) => return PamResult::error(PamError::StartFailed, error.to_string()),
479 };
480 match transaction.authenticate(AuthnFlags::empty()) {
481 Ok(()) => {
482 if let Err(error) = transaction.account_management(AuthnFlags::empty()) {
485 tracing::warn!(%error, "PAM's account check refused after authenticating");
486 }
487 PamResult::Success
488 }
489 Err(error) => tried(error),
490 }
491 }
492}
493
494fn tried(error: ErrorCode) -> PamResult {
496 let kind = match error {
497 ErrorCode::AuthenticationError => return PamResult::Failure,
498 ErrorCode::ConversationError => PamError::InternalError,
500 _ => PamError::TryAuthFailed,
501 };
502 PamResult::error(kind, error.to_string())
503}
504
505struct Adapter<'a>(&'a Talk);
509
510impl Adapter<'_> {
511 fn answer(&self, question: &OsStr, visible: bool) -> nonstick::Result<OsString> {
514 let secret = self
515 .0
516 .ask(question, visible)
517 .ok_or(ErrorCode::ConversationError)?;
518 if secret.bytes().contains(&0) {
520 tracing::warn!("PAM was refused a response with a NUL in it");
521 return Err(ErrorCode::ConversationError);
522 }
523 Ok(OsStr::from_bytes(secret.bytes()).to_owned())
526 }
527}
528
529impl ConversationAdapter for Adapter<'_> {
530 fn prompt(&self, request: impl AsRef<OsStr>) -> nonstick::Result<OsString> {
531 self.answer(request.as_ref(), true)
532 }
533
534 fn masked_prompt(&self, request: impl AsRef<OsStr>) -> nonstick::Result<OsString> {
535 self.answer(request.as_ref(), false)
536 }
537
538 fn error_msg(&self, message: impl AsRef<OsStr>) {
539 self.0.tell(PamMessage::Error, message.as_ref());
540 }
541
542 fn info_msg(&self, message: impl AsRef<OsStr>) {
543 self.0.tell(PamMessage::Info, message.as_ref());
544 }
545}
546
547fn set<T: PartialEq + 'static>(signal: Signal<T>, value: T) {
550 if untrack(|| signal.try_with(|old| *old != value)) == Some(true) {
551 signal.try_set(value);
552 }
553}