Debian Codegraph @

src/libpam.rs

raw symbols SCIP
1 #![allow(dead_code)]
2
3 use pam::{Pam, PamError, PamFlags};
4 use pam_types::{LogLvl, PamConv, PamHandle, PamItemType, PamMessage, PamMsgStyle, PamResponse};
5 use std::ffi::{CStr, CString, NulError};
6 use std::ops::Deref;
7 use std::option::Option;
8 use std::os::raw::{c_char, c_int, c_void};
9 use std::ptr;
10
11 pub type PamResult<T> = Result<T, PamError>;
12 /// Prototype of the callback used with [`PamLibExt::send_bytes`]
13 pub type PamCleanupCb = fn(&Vec<u8>, Pam, PamFlags, PamError);
14
15 #[derive(Clone)]
16 struct PamByteData {
17 cb: Option<PamCleanupCb>,
18 data: Vec<u8>,
19 }
20
21 /// Trait to implement for data stored with pam using [`PamLibExt::send_data`]
22 /// in order to provide a cleanup callback.
23 /// # Example
24 /// ```
25 /// extern crate pamsm;
26 /// use pamsm::{Pam, PamData, PamError, PamFlags};
27 /// use std::fs::write;
28 ///
29 /// struct Token([u8; 32]);
30 ///
31 /// impl PamData for Token {
32 /// fn cleanup(&self, _pam: Pam, flags: PamFlags, status: PamError) {
33 /// if !flags.contains(PamFlags::DATA_REPLACE) && status == PamError::SUCCESS {
34 /// match write(".token.bin", self.0) {
35 /// Ok(_) => (),
36 /// Err(err) => {
37 /// if !flags.contains(PamFlags::SILENT) {
38 /// println!("Error persisting token : {:?}", err);
39 /// }
40 /// }
41 /// };
42 /// }
43 /// }
44 /// }
45 /// ```
46 pub trait PamData {
47 /// The cleanup method will be called before the data is dropped by pam.
48 /// See `pam_set_data (3)`
49 fn cleanup(&self, _pam: Pam, _flags: PamFlags, _status: PamError) {}
50 }
51
52 impl PamData for PamByteData {
53 fn cleanup(&self, pam: Pam, flags: PamFlags, status: PamError) {
54 if let Some(cb) = self.cb {
55 (cb)(&self.data, pam, flags, status);
56 }
57 }
58 }
59
60 /// Blanket implementation for types that implement `Deref<T>` when `T` implements `PamData`.
61 impl<T: PamData, U> PamData for U
62 where
63 U: Deref<Target = T>,
64 {
65 fn cleanup(&self, pam: Pam, flags: PamFlags, status: PamError) {
66 T::cleanup(self, pam, flags, status)
67 }
68 }
69
70 impl PamError {
71 fn to_result<T>(self, ok: T) -> PamResult<T> {
72 if self == PamError::SUCCESS {
73 Ok(ok)
74 } else {
75 Err(self)
76 }
77 }
78 }
79
80 /// This contains a private marker trait, used to seal private traits.
81 mod private {
82 pub trait Sealed {}
83 impl Sealed for super::Pam {}
84 }
85
86 impl Pam {
87 // End users should call the item specific methods
88 fn get_cstr_item(&self, item_type: PamItemType) -> PamResult<Option<&CStr>> {
89 match item_type {
90 PamItemType::CONV | PamItemType::FAIL_DELAY | PamItemType::XAUTHDATA => {
91 panic!("Error, get_cstr_item can only be used with pam item returning c-strings")
92 }
93 _ => (),
94 }
95 let mut raw_item: *const c_void = ptr::null();
96 let r = unsafe { PamError::new(pam_get_item(self.0, item_type as c_int, &mut raw_item)) };
97 if raw_item.is_null() {
98 r.to_result(None)
99 } else {
100 // pam should keep the underlying token allocated during the lifetime of the module
101 r.to_result(Some(unsafe { CStr::from_ptr(raw_item as *const c_char) }))
102 }
103 }
104 }
105
106 /// Extension trait over `Pam`, usually provided by the `libpam` shared library.
107 pub trait PamLibExt: private::Sealed {
108 /// Get the username. If the PAM_USER item is not set, this function
109 /// prompts for a username (like get_authtok).
110 /// Returns PamError::SERVICE_ERR if the prompt contains any null byte
111 fn get_user(&self, prompt: Option<&str>) -> PamResult<Option<&CStr>>;
112
113 /// Get the username, i.e. the PAM_USER item. If it's not set return None.
114 fn get_cached_user(&self) -> PamResult<Option<&CStr>>;
115
116 /// Get the cached authentication token.
117 fn get_cached_authtok(&self) -> PamResult<Option<&CStr>>;
118
119 /// Get the cached old authentication token.
120 fn get_cached_oldauthtok(&self) -> PamResult<Option<&CStr>>;
121
122 /// Get the cached authentication token or prompt the user for one if there isn't any.
123 /// Returns PamError::SERVICE_ERR if the prompt contains any null byte
124 fn get_authtok(&self, prompt: Option<&str>) -> PamResult<Option<&CStr>>;
125
126 fn set_authtok(&self, authtok: &CString) -> PamResult<()>;
127
128 /// Get the remote hostname.
129 fn get_rhost(&self) -> PamResult<Option<&CStr>>;
130
131 /// Get the remote username.
132 fn get_ruser(&self) -> PamResult<Option<&CStr>>;
133
134 /// Get the service name.
135 fn get_service(&self) -> PamResult<Option<&CStr>>;
136
137 /// Prompt the user for custom input.
138 /// Returns PamError::SERVICE_ERR if the prompt contains any null byte
139 fn conv(&self, prompt: Option<&str>, style: PamMsgStyle) -> PamResult<Option<&CStr>>;
140
141 /// Get a variable from the pam environment list.
142 fn getenv(&self, name: &str) -> PamResult<Option<&CStr>>;
143
144 /// Put a variable in the pam environment list.
145 /// `name_value` takes for form documented in pam_putent(3) :
146 ///
147 /// - `NAME=value` will set variable `NAME` to value `value`
148 /// - `NAME=` will set variable `NAME` to an empty value
149 /// - `NAME` will unset the variable `NAME`
150 fn putenv(&self, name_value: &str) -> PamResult<()>;
151
152 /// Send data to be stored by the pam library under the name `module_name`.
153 /// The data can then be retrieved from a different
154 /// callback in this module, or even by a different module
155 /// using [`retrieve_data<T>`][Self::retrieve_data].
156 ///
157 /// When this method is called a second time with the same `module_name`, the method
158 /// [`PamData::cleanup`] is called on the data previously stored.
159 /// The same happens when the application calls `pam_end (3)`
160 ///
161 /// If your data can be converted into / from [`Vec<u8>`][std::vec::Vec]
162 /// you should consider using the [`send_bytes`][Self::send_bytes] method instead.
163 ///
164 /// # Safety
165 /// This method should not be used if the [`send_bytes`][Self::send_bytes] method is also used
166 /// with the same `module_name`.
167 unsafe fn send_data<T: PamData + Clone + Send>(
168 &self,
169 module_name: &str,
170 data: T,
171 ) -> PamResult<()>;
172
173 /// Retrieve data previously stored with [`send_data<T>`][Self::send_data].
174 ///
175 /// Note that the result is a _copy_ of the data and not a shared reference,
176 /// which differs from the behavior of the underlying `pam_get_data (3)` function.
177 ///
178 /// If you want to share the data instead you can wrap it in [`Arc`][std::sync::Arc].
179 /// # Safety
180 /// The type parameter `T` must be the same as the one used in
181 /// [`send_data<T>`][Self::send_data] with the name `module_name`.
182 ///
183 /// If the data was stored with [`send_bytes`][Self::send_bytes] you must use
184 /// [`retrieve_bytes`][Self::retrieve_bytes] instead.
185 unsafe fn retrieve_data<T: PamData + Clone + Send>(&self, module_name: &str) -> PamResult<T>;
186
187 /// Similar to [`send_data`][Self::send_data], but only works with [`Vec<u8>`][std::vec::Vec].
188 /// The PamData trait doesn't have to be implemented on the data, a callback can be passed
189 /// as an argument instead.
190 fn send_bytes(
191 &self,
192 module_name: &str,
193 data: Vec<u8>,
194 cb: Option<PamCleanupCb>,
195 ) -> PamResult<()>;
196
197 /// Retrieve bytes previously stored with [`send_bytes`][Self::send_bytes].
198 /// The result is a clone of the data.
199 fn retrieve_bytes(&self, module_name: &str) -> PamResult<Vec<u8>>;
200
201 /// Send a message to syslog.
202 fn syslog(&self, lvl: LogLvl, msg: &str) -> PamResult<()>;
203 }
204
205 impl From<NulError> for PamError {
206 fn from(_: NulError) -> PamError {
207 PamError::SERVICE_ERR
208 }
209 }
210
211 impl PamLibExt for Pam {
212 fn get_user(&self, prompt: Option<&str>) -> PamResult<Option<&CStr>> {
213 let cprompt = match prompt {
214 None => None,
215 Some(p) => Some(CString::new(p)?),
216 };
217 let mut raw_user: *const c_char = ptr::null();
218 let r = unsafe {
219 PamError::new(pam_get_user(
220 self.0,
221 &mut raw_user,
222 cprompt.as_ref().map_or(ptr::null(), |p| p.as_ptr()),
223 ))
224 };
225
226 if raw_user.is_null() {
227 r.to_result(None)
228 } else {
229 r.to_result(Some(unsafe { CStr::from_ptr(raw_user) }))
230 }
231 }
232
233 fn get_cached_user(&self) -> PamResult<Option<&CStr>> {
234 self.get_cstr_item(PamItemType::USER)
235 }
236
237 fn get_cached_authtok(&self) -> PamResult<Option<&CStr>> {
238 self.get_cstr_item(PamItemType::AUTHTOK)
239 }
240
241 fn get_cached_oldauthtok(&self) -> PamResult<Option<&CStr>> {
242 self.get_cstr_item(PamItemType::OLDAUTHTOK)
243 }
244
245 fn get_authtok(&self, prompt: Option<&str>) -> PamResult<Option<&CStr>> {
246 let cprompt = match prompt {
247 None => None,
248 Some(p) => Some(CString::new(p)?),
249 };
250 let mut raw_at: *const c_char = ptr::null();
251 let r = unsafe {
252 PamError::new(pam_get_authtok(
253 self.0,
254 PamItemType::AUTHTOK as i32,
255 &mut raw_at,
256 cprompt.as_ref().map_or(ptr::null(), |p| p.as_ptr()),
257 ))
258 };
259
260 if raw_at.is_null() {
261 r.to_result(None)
262 } else {
263 r.to_result(unsafe { Some(CStr::from_ptr(raw_at)) })
264 }
265 }
266
267 fn set_authtok(&self, authtok: &CString) -> PamResult<()> {
268 unsafe {
269 set_item(
270 self.0,
271 PamItemType::AUTHTOK,
272 authtok.as_ptr() as *const c_void,
273 )
274 }
275 }
276
277 fn get_rhost(&self) -> PamResult<Option<&CStr>> {
278 self.get_cstr_item(PamItemType::RHOST)
279 }
280
281 fn get_ruser(&self) -> PamResult<Option<&CStr>> {
282 self.get_cstr_item(PamItemType::RUSER)
283 }
284
285 fn get_service(&self) -> PamResult<Option<&CStr>> {
286 self.get_cstr_item(PamItemType::SERVICE)
287 }
288
289 fn conv(&self, prompt: Option<&str>, style: PamMsgStyle) -> PamResult<Option<&CStr>> {
290 let mut conv_pointer: *const c_void = ptr::null();
291 let r = unsafe {
292 PamError::new(pam_get_item(
293 self.0,
294 PamItemType::CONV as c_int,
295 &mut conv_pointer,
296 ))
297 };
298
299 if r != PamError::SUCCESS {
300 return Err(r);
301 }
302
303 if conv_pointer.is_null() {
304 return Ok(None);
305 }
306
307 let conv = unsafe { &*(conv_pointer as *const PamConv) };
308 let mut resp_ptr: *mut PamResponse = ptr::null_mut();
309 let msg_cstr = CString::new(prompt.unwrap_or(""))?;
310 let msg = PamMessage {
311 msg_style: style,
312 msg: msg_cstr.as_ptr(),
313 };
314
315 match conv.cb.map(|cb| {
316 PamError::new(cb(
317 1,
318 &mut (&msg as *const PamMessage),
319 &mut resp_ptr,
320 conv.appdata_ptr,
321 ))
322 }) {
323 Some(PamError::SUCCESS) => {
324 Ok(unsafe { (*resp_ptr).resp }.map(|r| unsafe { CStr::from_ptr(r.as_ptr()) }))
325 }
326 Some(ret) => Err(ret),
327 None => Ok(None),
328 }
329 }
330
331 fn getenv(&self, name: &str) -> PamResult<Option<&CStr>> {
332 let cname = CString::new(name)?;
333 let cenv = unsafe { pam_getenv(self.0, cname.as_ptr()) };
334
335 if cenv.is_null() {
336 Ok(None)
337 } else {
338 unsafe { Ok(Some(CStr::from_ptr(cenv))) }
339 }
340 }
341
342 fn putenv(&self, name_value: &str) -> PamResult<()> {
343 let cenv = CString::new(name_value)?;
344 unsafe { PamError::new(pam_putenv(self.0, cenv.as_ptr())).to_result(()) }
345 }
346
347 unsafe fn send_data<T: PamData + Clone + Send>(
348 &self,
349 module_name: &str,
350 data: T,
351 ) -> PamResult<()> {
352 // The data has to be allocated on the heap because it will outlive the call stack.
353 let data_copy = Box::new(data);
354 PamError::new(pam_set_data(
355 self.0,
356 CString::new(module_name)?.as_ptr(),
357 Box::into_raw(data_copy) as *mut c_void,
358 Some(pam_data_cleanup::<T>),
359 ))
360 .to_result(())
361 }
362
363 unsafe fn retrieve_data<T: PamData + Clone + Send>(&self, module_name: &str) -> PamResult<T> {
364 let mut data_ptr: *const c_void = ptr::null();
365 // pam_get_data should be safe as long as T is the type that what used in send_data.
366 PamError::new(pam_get_data(
367 self.0,
368 CString::new(module_name)?.as_ptr(),
369 &mut data_ptr,
370 ))
371 .to_result(data_ptr as *const T)
372 .map(|ptr| (*ptr).clone()) // pam guaranties the data is valid when SUCCESS is returned.
373 }
374
375 fn send_bytes(
376 &self,
377 module_name: &str,
378 data: Vec<u8>,
379 cb: Option<PamCleanupCb>,
380 ) -> PamResult<()> {
381 let data_cb = PamByteData { cb, data };
382 unsafe { self.send_data(module_name, data_cb) }
383 }
384
385 fn retrieve_bytes(&self, module_name: &str) -> PamResult<Vec<u8>> {
386 unsafe { self.retrieve_data::<PamByteData>(module_name) }.map(|data_cb| data_cb.data)
387 }
388
389 fn syslog(&self, lvl: LogLvl, msg: &str) -> PamResult<()> {
390 let fmt = b"%s\0".as_ptr() as *const c_char;
391 let cmsg = CString::new(msg)?;
392 unsafe {
393 pam_syslog(self.0, lvl as c_int, fmt, cmsg.as_ptr());
394 }
395 Ok(())
396 }
397 }
398
399 unsafe extern "C" fn pam_data_cleanup<T: PamData + Clone + Send>(
400 handle: PamHandle,
401 data: *mut c_void,
402 error_status: c_int,
403 ) {
404 Box::from_raw(data as *mut T).cleanup(
405 Pam(handle),
406 PamFlags::from_bits_truncate(error_status),
407 PamError::new(error_status & 0xff),
408 );
409 }
410
411 unsafe fn set_item(pamh: PamHandle, item_type: PamItemType, item: *const c_void) -> PamResult<()> {
412 PamError::new(pam_set_item(pamh, item_type as c_int, item)).to_result(())
413 }
414
415 // Raw functions
416 #[link(name = "pam")]
417 extern "C" {
418 pub fn pam_set_item(pamh: PamHandle, item_type: c_int, item: *const c_void) -> c_int;
419 pub fn pam_get_item(pamh: PamHandle, item_type: c_int, item: *mut *const c_void) -> c_int;
420 pub fn pam_strerror(pamh: PamHandle, errnum: c_int) -> *const c_char;
421 pub fn pam_putenv(pamh: PamHandle, name_value: *const c_char) -> c_int;
422 pub fn pam_getenv(pamh: PamHandle, name: *const c_char) -> *const c_char;
423 pub fn pam_getenvlist(pamh: PamHandle) -> *mut *mut c_char;
424
425 pub fn pam_set_data(
426 pamh: PamHandle,
427 module_data_name: *const c_char,
428 data: *mut c_void,
429 cleanup: Option<unsafe extern "C" fn(_: PamHandle, _: *mut c_void, _: c_int)>,
430 ) -> c_int;
431 pub fn pam_get_data(
432 pamh: PamHandle,
433 module_data_name: *const c_char,
434 data: *mut *const c_void,
435 ) -> c_int;
436 pub fn pam_get_user(pamh: PamHandle, user: *mut *const c_char, prompt: *const c_char) -> c_int;
437 pub fn pam_get_authtok(
438 pamh: PamHandle,
439 item: c_int,
440 authok_ptr: *mut *const c_char,
441 prompt: *const c_char,
442 ) -> c_int;
443
444 pub fn pam_syslog(pamh: PamHandle, priority: c_int, fmt: *const c_char, ...) -> c_void;
445 }