Skip to main content

crabshell_services/
pam.rs

1//! PAM authentication, as Quickshell's `PamContext`, for lock screens.
2
3#[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
20/// The longest question or message passed on, in bytes. The rest is cut.
21const MAX_TEXT: usize = 4096;
22
23/// The most messages one attempt keeps; older ones go.
24pub(crate) const MAX_MESSAGES: usize = 64;
25
26/// What `cx.pam` needs from the shell: the loop and the backend.
27pub(crate) struct Service(pub(crate) Rc<Shared>);
28
29/// Where an authentication is, from [`Pam::state`].
30#[derive(Clone, Debug, PartialEq)]
31pub enum PamState {
32  /// Nothing started, or the last attempt was aborted.
33  Idle,
34  /// PAM asks `message`, such as `Password: `, and waits for
35  /// [`Pam::respond`].
36  Asking {
37    /// The question, cut to 4 KiB.
38    message: String,
39    /// Whether the answer may show as it is typed: `false` for a
40    /// password.
41    visible: bool,
42  },
43  /// PAM is working, as between an answer and the next question.
44  Busy,
45  /// The attempt ended.
46  Done(PamResult),
47}
48
49/// How an attempt ended.
50#[derive(Clone, Debug, PartialEq)]
51pub enum PamResult {
52  /// The user is who they said.
53  Success,
54  /// PAM refused the answers, as for a wrong password.
55  Failure,
56  /// Something kept PAM from deciding, such as an unknown user.
57  Error {
58    /// Where it went wrong.
59    kind: PamError,
60    /// What went wrong, in PAM's words or the shell's.
61    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/// Where an attempt that ended in [`PamResult::Error`] went wrong.
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum PamError {
75  /// It never began: libpam refused to start the service, a service or
76  /// user name held a NUL, or NSS doesn't know the shell's own user.
77  StartFailed,
78  /// PAM couldn't try the answers, which isn't the user failing to
79  /// authenticate: `pam_authenticate` returned an error but
80  /// `PAM_AUTH_ERR`, which is [`Failure`](PamResult::Failure), and
81  /// `PAM_CONV_ERR`, such as `PAM_USER_UNKNOWN`, `PAM_AUTHINFO_UNAVAIL`
82  /// or `PAM_MAXTRIES`.
83  TryAuthFailed,
84  /// The shell's side failed: it refused PAM an answer, as one with a
85  /// NUL, or the attempt ended without a result.
86  InternalError,
87}
88
89/// A line PAM sent during an attempt, from [`Pam::messages`], cut to
90/// 4 KiB.
91#[derive(Clone, Debug, PartialEq)]
92pub enum PamMessage {
93  /// Something to show, such as how to use a fingerprint reader.
94  Info(String),
95  /// Something that went wrong, such as a locked account.
96  Error(String),
97}
98
99/// Authentication through a PAM service, from `cx.pam(service)`, as a lock
100/// screen does. A clone is cheap and shares it.
101///
102/// libpam blocks, so each attempt runs on a thread of its own, and the
103/// loop hears from it only while it runs: an idle `Pam` wakes nothing. When
104/// the context that made it goes, an attempt still running is refused its
105/// answer, so its thread ends.
106#[derive(Clone)]
107pub struct Pam {
108  inner: Rc<Inner>,
109}
110
111struct Inner {
112  /// `None` when the shell provided no services.
113  shared: Option<Rc<Shared>>,
114  service: String,
115  /// These live under the asking context's owner.
116  state: Signal<PamState>,
117  messages: Signal<Vec<PamMessage>>,
118  attempt: RefCell<Option<Attempt>>,
119  /// The loop source of an aborted attempt whose thread is still inside
120  /// PAM, as one a fingerprint module holds, until that thread returns.
121  abandoned: RefCell<Option<RegistrationToken>>,
122  /// The user a start named while that thread ran, which begins once it
123  /// returns.
124  waiting: RefCell<Option<Option<String>>>,
125  /// The number the next attempt gets.
126  next: Cell<u64>,
127}
128
129/// The attempt running now.
130struct Attempt {
131  /// Which attempt this is, so the events of an aborted one are told
132  /// apart.
133  number: u64,
134  /// The loop source its thread's events arrive on.
135  source: RegistrationToken,
136  /// Where answers go. Dropping it refuses the question its thread waits
137  /// on.
138  answers: mpsc::Sender<Secret>,
139  /// A question waits for its answer.
140  asking: bool,
141}
142
143/// What an attempt's thread tells the loop.
144pub(crate) enum Event {
145  Ask { message: String, visible: bool },
146  Tell(PamMessage),
147  Done(PamResult),
148}
149
150/// What authenticates, off the loop's thread: libpam, or a test's script.
151pub(crate) trait Backend: Send + Sync {
152  /// Authenticates `user` for `service`, asking and telling through
153  /// `talk`.
154  fn authenticate(&self, service: &str, user: &str, talk: &Talk) -> PamResult;
155}
156
157/// An attempt's end of the conversation, on its thread.
158pub(crate) struct Talk {
159  events: calloop::channel::Sender<Event>,
160  answers: mpsc::Receiver<Secret>,
161}
162
163impl Talk {
164  /// Asks the config `question`, cut to 4 KiB, and waits for the answer.
165  /// `None` when it was refused: the attempt was aborted, its context
166  /// went, or the shell is gone.
167  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  /// Passes `text`, cut to 4 KiB, on as a message.
174  pub(crate) fn tell(&self, kind: fn(String) -> PamMessage, text: &OsStr) {
175    // Refused once the attempt is gone, when nobody reads it.
176    let _ = self.events.send(Event::Tell(kind(cut(text))));
177  }
178}
179
180/// `text` as UTF-8 with bad bytes replaced, cut to [`MAX_TEXT`] bytes on
181/// a character's boundary.
182fn 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
188/// An answer on its way to libpam. Its bytes are zeroed when it drops, and
189/// it has no `Debug`, so it can't be logged.
190pub(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
204/// Zeroes every byte `bytes` holds room for.
205pub(crate) fn wipe(bytes: &mut Vec<u8>) {
206  bytes.clear();
207  bytes.resize(bytes.capacity(), 0);
208  // So the compiler can't drop the writes as dead before the free.
209  std::hint::black_box(bytes);
210}
211
212/// `cx.pam(service)`.
213pub(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  // Dropped with the asking context's owner, which ends the attempt.
232  cx.owner().signal(EndOnDrop(Rc::clone(&inner)));
233  Pam { inner }
234}
235
236/// Ends the attempt when the asking context's owner drops it.
237struct 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  /// Starts authenticating `user`, or with `None` the user the shell runs
251  /// as, found by its uid. An attempt already running is aborted first.
252  ///
253  /// PAM can't be stopped while a module blocks without asking, as a
254  /// fingerprint reader waits for a finger, so an aborted attempt's
255  /// thread stays inside PAM until the module returns. A start meanwhile
256  /// shows [`Busy`](PamState::Busy) and begins once it has, so two
257  /// transactions never run side by side.
258  ///
259  /// Ending an attempt while PAM waits for an answer, by aborting it,
260  /// starting another or dropping its context, counts as a failed login
261  /// where `pam_faillock` counts failures, and enough of them lock the
262  /// account. So take the password first, start on Enter, and answer as
263  /// soon as PAM asks.
264  pub fn start(&self, user: Option<&str>) {
265    self.inner.abort();
266    self.inner.start(user.map(str::to_owned));
267  }
268
269  /// Answers the question asked, and the state turns
270  /// [`Busy`](PamState::Busy). The answer is never logged, and its bytes
271  /// are zeroed once handed on, but the copy made for libpam is freed
272  /// unzeroed. With no question waiting, it is dropped, and that is
273  /// logged.
274  pub fn respond(&self, text: impl Into<String>) {
275    self.inner.respond(Secret(text.into().into_bytes()));
276  }
277
278  /// Stops the attempt running: the state turns [`Idle`](PamState::Idle)
279  /// at once, its question is refused and its result is never shown.
280  /// Its thread ends at PAM's next question, or once a module that
281  /// blocks without asking returns. A start waiting for that is dropped.
282  /// With nothing running, nothing changes. A refused question counts as
283  /// a failed login, as [`start`](Self::start) says.
284  pub fn abort(&self) {
285    self.inner.abort();
286  }
287
288  /// Where the attempt is.
289  pub fn state(&self) -> ReadSignal<PamState> {
290    self.inner.state.read_only()
291  }
292
293  /// The info and error lines PAM sent during the attempt, oldest first.
294  /// Each start empties it.
295  pub fn messages(&self) -> ReadSignal<Vec<PamMessage>> {
296    self.inner.messages.read_only()
297  }
298}
299
300impl Inner {
301  /// Whether the asking context is still there. Untracked, so an effect
302  /// that starts an attempt doesn't run again for it.
303  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        // Refused when the attempt was aborted meanwhile.
344        let _ = talk.events.send(Event::Done(result));
345      });
346    if let Err(error) = spawned {
347      // Its channel closed with it, which ends the attempt.
348      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      // An aborted attempt's: only its end matters.
364      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      // The thread ended before its result, as when it panicked.
386      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        // `secret` is zeroed as it drops.
398        return tracing::warn!("PAM asked no question, so a response was dropped");
399      };
400      attempt.asking = false;
401      // Fails only once the thread is gone, and drops `secret`, zeroed.
402      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  /// Abandons the attempt running: dropping its sender refuses the
414  /// question its thread waits on, and its source stays only to hear that
415  /// thread return. A start waiting is dropped.
416  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  /// An aborted attempt's thread returned: its source leaves the loop, and
428  /// a start that waited for it begins.
429  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  /// Ends the attempt running, if one is: its source leaves the loop, and
440  /// dropping its sender refuses the question its thread waits on. Whether
441  /// one ran.
442  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
457/// The name of the user the shell runs as, found by its uid through NSS,
458/// since `$USER` is whatever the shell's parent set.
459fn 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
464/// The system's libpam.
465pub(crate) struct LibPam;
466
467impl Backend for LibPam {
468  fn authenticate(&self, service: &str, user: &str, talk: &Talk) -> PamResult {
469    // libpam takes C strings, and nonstick panics on a NUL.
470    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        // The account step is where `pam_faillock` forgets past failures.
483        // Its refusal, as for an expired password, is only logged.
484        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
494/// What `pam_authenticate` failing with `error` means.
495fn tried(error: ErrorCode) -> PamResult {
496  let kind = match error {
497    ErrorCode::AuthenticationError => return PamResult::Failure,
498    // Only the shell's conversation fails so: it refused an answer.
499    ErrorCode::ConversationError => PamError::InternalError,
500    _ => PamError::TryAuthFailed,
501  };
502  PamResult::error(kind, error.to_string())
503}
504
505/// libpam's questions and messages, through an attempt's [`Talk`]. It runs
506/// inside libpam's callback, where a panic aborts the shell, so nothing in
507/// it panics.
508struct Adapter<'a>(&'a Talk);
509
510impl Adapter<'_> {
511  /// The config's answer to `question`, copied for libpam. Ours is zeroed
512  /// as it drops.
513  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    // nonstick panics on a NUL, and libpam would read only up to it.
519    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    // shortcut: nonstick frees this copy without zeroing it; zero it too if
524    // nonstick ever takes answers in a buffer it wipes.
525    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
547/// Sets `signal` to `value` unless it holds it already, so nothing wakes
548/// for a value that didn't change.
549fn 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}