limes-common 0.3.0

Shared authentication, config, events, and errors for limes crates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::ffi::{CStr, CString, c_void};

use limes_proto::{LimesEvent, PamMessageKind};
use zeroize::Zeroize;

use crate::auth::pam::raw as pam;
use crate::events::EventBus;

pub(super) struct SecretCString {
    bytes: Vec<u8>,
}

impl SecretCString {
    pub(super) fn new(value: &str) -> std::result::Result<Self, std::ffi::NulError> {
        CString::new(value).map(|value| Self {
            bytes: value.into_bytes_with_nul(),
        })
    }

    fn as_ptr(&self) -> *const libc::c_char {
        self.bytes.as_ptr().cast()
    }
}

impl Drop for SecretCString {
    fn drop(&mut self) {
        self.bytes.zeroize();
    }
}

pub(super) struct PamConversation {
    username: CString,
    username_string: String,
    password: Option<SecretCString>,
    events: Option<EventBus>,
    pending: Vec<LimesEvent>,
    #[cfg(test)]
    panic_after_reply: bool,
}

impl PamConversation {
    pub(super) fn new(
        username: CString,
        username_string: String,
        password: Option<SecretCString>,
        events: Option<EventBus>,
    ) -> Self {
        Self {
            username,
            username_string,
            password,
            events,
            pending: Vec::new(),
            #[cfg(test)]
            panic_after_reply: false,
        }
    }

    pub(super) fn username_ptr(&self) -> *const libc::c_char {
        self.username.as_ptr()
    }

    fn password_ptr(&self) -> Option<*const libc::c_char> {
        self.password.as_ref().map(SecretCString::as_ptr)
    }

    pub(super) fn clear_password(&mut self) {
        self.password = None;
    }

    fn queue_message(&mut self, kind: PamMessageKind, message: &str) {
        if self.events.is_some() {
            self.pending.push(LimesEvent::AuthPamMessage {
                username: self.username_string.clone(),
                kind,
                message: message.to_owned(),
            });
        }
    }

    /// Drain only after PAM has returned to Rust; observers never run inside C.
    pub(super) fn dispatch_messages(&mut self) {
        let pending = std::mem::take(&mut self.pending);
        if let Some(events) = &self.events {
            for event in pending {
                events.emit(event);
            }
        }
    }
}

pub(super) extern "C" fn pam_conversation(
    num_msg: libc::c_int,
    msg: *mut *const pam::PamMessage,
    resp: *mut *mut pam::PamResponse,
    appdata_ptr: *mut c_void,
) -> libc::c_int {
    if num_msg <= 0 || msg.is_null() || resp.is_null() || appdata_ptr.is_null() {
        return pam::PAM_CONV_ERR;
    }

    unsafe { *resp = std::ptr::null_mut() };
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        conversation_inner(num_msg, msg, resp, appdata_ptr)
    })) {
        Ok(status) => status,
        Err(payload) => {
            // A panic payload's destructor may itself panic. Never unwind into C.
            std::mem::forget(payload);
            pam::PAM_CONV_ERR
        }
    }
}

struct Replies {
    ptr: *mut pam::PamResponse,
    count: isize,
}

impl Drop for Replies {
    fn drop(&mut self) {
        free_pam_replies(self.ptr, self.count);
    }
}

fn conversation_inner(
    num_msg: libc::c_int,
    msg: *mut *const pam::PamMessage,
    resp: *mut *mut pam::PamResponse,
    appdata_ptr: *mut c_void,
) -> libc::c_int {
    let replies = unsafe { libc::calloc(num_msg as usize, std::mem::size_of::<pam::PamResponse>()) }
        as *mut pam::PamResponse;
    if replies.is_null() {
        return pam::PAM_BUF_ERR;
    }

    // calloc initialized every response pointer; the guard covers partial
    // replies on every error and while unwinding to the FFI panic boundary.
    let guard = Replies {
        ptr: replies,
        count: num_msg as isize,
    };
    let state = unsafe { &mut *(appdata_ptr.cast::<PamConversation>()) };
    for index in 0..num_msg as isize {
        let message = unsafe { *msg.offset(index) };
        if message.is_null() {
            return pam::PAM_CONV_ERR;
        }

        let style = unsafe { (*message).msg_style };
        let message_text = pam_message_text(message);
        if let Some(kind) = pam_message_kind(style) {
            state.queue_message(kind, &message_text);
        }

        let response = match style {
            pam::PAM_PROMPT_ECHO_ON => Some(state.username_ptr()),
            pam::PAM_PROMPT_ECHO_OFF => {
                let Some(password) = state.password_ptr() else {
                    return pam::PAM_CONV_ERR;
                };
                Some(password)
            }
            pam::PAM_ERROR_MSG | pam::PAM_TEXT_INFO => None,
            _ => {
                return pam::PAM_CONV_ERR;
            }
        };

        if let Some(response) = response {
            let duplicated = unsafe { libc::strdup(response) };
            if duplicated.is_null() {
                return pam::PAM_BUF_ERR;
            }
            unsafe { (*replies.offset(index)).resp = duplicated };
            #[cfg(test)]
            if state.panic_after_reply {
                panic!("injected callback panic after response allocation");
            }
        }
    }

    unsafe { *resp = replies };
    std::mem::forget(guard); // PAM now owns the successful responses.
    pam::PAM_SUCCESS
}

pub(super) fn free_pam_replies(replies: *mut pam::PamResponse, initialized: isize) {
    for index in 0..initialized {
        let response = unsafe { (*replies.offset(index)).resp };
        if !response.is_null() {
            // These failure-path replies are still ours, unlike successful
            // replies transferred to PAM. Wipe credentials before freeing.
            let len = unsafe { libc::strlen(response) };
            unsafe { std::slice::from_raw_parts_mut(response.cast::<u8>(), len) }.zeroize();
            unsafe { libc::free(response.cast()) };
        }
    }
    unsafe { libc::free(replies.cast()) };
}

fn pam_message_kind(style: libc::c_int) -> Option<PamMessageKind> {
    match style {
        pam::PAM_PROMPT_ECHO_ON => Some(PamMessageKind::PromptEchoOn),
        pam::PAM_PROMPT_ECHO_OFF => Some(PamMessageKind::PromptEchoOff),
        pam::PAM_TEXT_INFO => Some(PamMessageKind::TextInfo),
        pam::PAM_ERROR_MSG => Some(PamMessageKind::Error),
        _ => None,
    }
}

fn pam_message_text(message: *const pam::PamMessage) -> String {
    let text = unsafe { (*message).msg };
    if text.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(text) }
            .to_string_lossy()
            .into_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ptr;
    use std::sync::{Arc, Mutex};

    use crate::events::EventSink;

    #[derive(Default)]
    struct CapturingSink {
        events: Mutex<Vec<LimesEvent>>,
    }

    impl EventSink for CapturingSink {
        fn emit(&self, event: &LimesEvent) {
            self.events.lock().unwrap().push(event.clone());
        }
    }

    #[test]
    fn pam_conversation_answers_password_prompt_while_secret_is_present() {
        let mut conversation = test_conversation("alice", Some("secret"), None);
        let message_text = CString::new("Password:").unwrap();
        let message = pam::PamMessage {
            msg_style: pam::PAM_PROMPT_ECHO_OFF,
            msg: message_text.as_ptr(),
        };

        let (status, responses) = call_conversation(&mut conversation, &[&message]);

        assert_eq!(status, pam::PAM_SUCCESS);
        let responses = responses.expect("PAM conversation should allocate responses");
        let response = unsafe { CStr::from_ptr((*responses).resp) };
        assert_eq!(response.to_str().unwrap(), "secret");
        free_pam_replies(responses, 1);
    }

    #[test]
    fn pam_conversation_rejects_password_prompt_after_secret_is_cleared() {
        let mut conversation = test_conversation("alice", Some("secret"), None);
        conversation.clear_password();
        let message_text = CString::new("Password:").unwrap();
        let message = pam::PamMessage {
            msg_style: pam::PAM_PROMPT_ECHO_OFF,
            msg: message_text.as_ptr(),
        };

        let (status, responses) = call_conversation(&mut conversation, &[&message]);

        assert_eq!(status, pam::PAM_CONV_ERR);
        assert!(responses.is_none());
    }

    #[test]
    fn pam_conversation_emits_info_messages_without_password() {
        let events = EventBus::new();
        let sink = Arc::new(CapturingSink::default());
        events.subscribe(sink.clone());
        let mut conversation = test_conversation("alice", None, Some(events));
        let message_text = CString::new("hello").unwrap();
        let message = pam::PamMessage {
            msg_style: pam::PAM_TEXT_INFO,
            msg: message_text.as_ptr(),
        };

        let (status, responses) = call_conversation(&mut conversation, &[&message]);

        assert_eq!(status, pam::PAM_SUCCESS);
        let responses = responses.expect("PAM conversation should allocate responses");
        assert!(unsafe { (*responses).resp }.is_null());
        free_pam_replies(responses, 1);

        assert!(sink.events.lock().unwrap().is_empty());
        conversation.dispatch_messages();
        let captured = sink.events.lock().unwrap();
        assert_eq!(
            *captured,
            vec![LimesEvent::AuthPamMessage {
                username: "alice".to_owned(),
                kind: PamMessageKind::TextInfo,
                message: "hello".to_owned(),
            }]
        );
    }

    struct PanickingSink;
    impl EventSink for PanickingSink {
        fn emit(&self, _: &LimesEvent) {
            panic!("observer panic outside FFI");
        }
    }

    #[test]
    fn observers_run_only_after_ffi_and_panics_do_not_affect_authentication() {
        let events = EventBus::new();
        let captured = Arc::new(CapturingSink::default());
        events.subscribe(Arc::new(PanickingSink));
        events.subscribe(captured.clone());
        let mut conversation = test_conversation("alice", Some("secret"), Some(events));
        let message = pam::PamMessage {
            msg_style: pam::PAM_PROMPT_ECHO_OFF,
            msg: ptr::null(),
        };
        let (status, replies) = call_conversation(&mut conversation, &[&message]);
        assert_eq!(status, pam::PAM_SUCCESS);
        assert!(captured.events.lock().unwrap().is_empty());
        free_pam_replies(replies.unwrap(), 1);
        conversation.dispatch_messages();
        assert_eq!(captured.events.lock().unwrap().len(), 1);
    }

    #[test]
    fn callback_panic_after_partial_reply_returns_error_without_unwinding_to_c() {
        let mut conversation = test_conversation("alice", Some("secret"), None);
        conversation.panic_after_reply = true;
        let message = pam::PamMessage {
            msg_style: pam::PAM_PROMPT_ECHO_OFF,
            msg: ptr::null(),
        };
        let (status, replies) = call_conversation(&mut conversation, &[&message]);
        assert_eq!(status, pam::PAM_CONV_ERR);
        assert!(replies.is_none());
        conversation.panic_after_reply = false;
        let (status, replies) = call_conversation(&mut conversation, &[&message]);
        assert_eq!(status, pam::PAM_SUCCESS);
        free_pam_replies(replies.unwrap(), 1);
    }

    #[test]
    fn pam_conversation_rejects_unsupported_message_styles() {
        let mut conversation = test_conversation("alice", Some("secret"), None);
        let unsupported = pam::PamMessage {
            msg_style: 999,
            msg: ptr::null(),
        };

        let (status, responses) = call_conversation(&mut conversation, &[&unsupported]);

        assert_eq!(status, pam::PAM_CONV_ERR);
        assert!(responses.is_none());
    }

    #[test]
    fn pam_conversation_rejects_unsupported_style_after_allocating_a_reply() {
        let mut conversation = test_conversation("alice", Some("secret"), None);
        let password = pam::PamMessage {
            msg_style: pam::PAM_PROMPT_ECHO_OFF,
            msg: ptr::null(),
        };
        let unsupported = pam::PamMessage {
            msg_style: 999,
            msg: ptr::null(),
        };

        let (status, responses) = call_conversation(&mut conversation, &[&password, &unsupported]);

        assert_eq!(status, pam::PAM_CONV_ERR);
        assert!(responses.is_none());
    }

    fn test_conversation(
        username: &str,
        password: Option<&str>,
        events: Option<EventBus>,
    ) -> PamConversation {
        PamConversation::new(
            CString::new(username).unwrap(),
            username.to_owned(),
            password.map(|password| SecretCString::new(password).unwrap()),
            events,
        )
    }

    fn call_conversation(
        conversation: &mut PamConversation,
        messages: &[&pam::PamMessage],
    ) -> (libc::c_int, Option<*mut pam::PamResponse>) {
        let mut raw_messages = messages
            .iter()
            .map(|message| *message as *const pam::PamMessage)
            .collect::<Vec<_>>();
        let mut responses = ptr::null_mut();
        let status = pam_conversation(
            raw_messages.len() as libc::c_int,
            raw_messages.as_mut_ptr(),
            &mut responses,
            (conversation as *mut PamConversation).cast(),
        );

        (
            status,
            if responses.is_null() {
                None
            } else {
                Some(responses)
            },
        )
    }
}