forked from fufesou/pam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.rs
348 lines (315 loc) · 12.5 KB
/
functions.rs
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
//! Wrapped FFI bindings to Linux-PAM
//!
//! Rustified wrappers around the unsafe PAM functions.
#[cfg(feature = "client")]
pub use appl::*;
#[cfg(feature = "module")]
pub use modules::*;
pub use types::*;
#[cfg(target_os = "freebsd")]
pub use misc::*;
/* ------------------------ <security/pam_appl.h> -------------------------- */
#[cfg(feature = "client")]
mod appl {
use crate::{PamFlag, PamHandle, PamResult, PamReturnCode};
use libc::c_int;
use pam_sys as ffi;
use std::ffi::CString;
/// Create the PAM context and initiate the PAM transaction
///
/// This needs to be called by an application to obtain a `PamHandle` which
/// contains any transaction state.
#[inline]
pub fn start<'a>(
service: &str,
user: Option<&str>,
conversation: &ffi::pam_conv,
) -> PamResult<&'a mut PamHandle> {
if let Ok(service) = CString::new(service) {
// Only service is required -> initialize handle
let mut handle: *mut PamHandle = std::ptr::null_mut();
let user_ptr = super::try_str_option_to_ptr(user)?;
match unsafe { ffi::pam_start(service.as_ptr(), user_ptr, conversation, &mut handle) }
.into()
{
// Reborrow is safe, because we check for null before
PamReturnCode::Success => {
assert!(
!handle.is_null(),
"Got PAM_SUCESS from pam_start but handle is null!"
);
Ok(unsafe { &mut *handle })
}
err => Err(err.into()),
}
} else {
// Invalid service
super::buffer_error()
}
}
/// Terminate the PAM transaction
///
/// This function has to be called last in the PAM context.
#[inline]
pub fn end(handle: &mut PamHandle, status: PamReturnCode) -> PamReturnCode {
// FIXME: Add PAM_DATA_SILENT argument?
unsafe { ffi::pam_end(handle, status as c_int) }.into()
}
/// Authenticate the user via the `Conversation` passed to `start`
///
/// Valid `PamFlag`s: Silent, Disallow_Null_AuthTok
#[inline]
pub fn authenticate(handle: &mut PamHandle, flags: PamFlag) -> PamReturnCode {
unsafe { ffi::pam_authenticate(handle, flags as c_int) }.into()
}
/// Modify the credentials of the user associated with the PAM transaction
///
/// This function should be called after the user has been authenticated and
/// before a session is opened.
///
/// Valid `PamFlag`s: Silent, {Establish,Delete,Reinitialize,Refresh}_Cred
#[inline]
pub fn setcred(handle: &mut PamHandle, flags: PamFlag) -> PamReturnCode {
unsafe { ffi::pam_setcred(handle, flags as c_int) }.into()
}
/// Determine if the user's account is valid
///
/// This function is typically called after a user has been authenticated.
///
/// Valid `PamFlag`s: Silent, Disallow_Null_AuthTok
#[inline]
pub fn acct_mgmt(handle: &mut PamHandle, flags: PamFlag) -> PamReturnCode {
unsafe { ffi::pam_acct_mgmt(handle, flags as c_int) }.into()
}
/// Set up a user session for a previously authenticated user
#[inline]
pub fn open_session(handle: &mut PamHandle, silent: bool) -> PamReturnCode {
let flag = silent as c_int;
unsafe { ffi::pam_open_session(handle, flag) }.into()
}
/// Indicate that an authenticated user session has ended
#[inline]
pub fn close_session(handle: &mut PamHandle, silent: bool) -> PamReturnCode {
let flag = silent as c_int;
unsafe { ffi::pam_close_session(handle, flag) }.into()
}
/// Change the authentication token for the user associated with the PAM
/// transaction
///
/// Valid `PamFlag`s: Silent, Change_Expired_AuthTok
#[inline]
pub fn chauthtok(handle: &mut PamHandle, flags: PamFlag) -> PamReturnCode {
unsafe { ffi::pam_chauthtok(handle, flags as c_int) }.into()
}
}
/* ------------------------ <security/pam_appl.h> -------------------------- */
/* ----------------------- <security/_pam_types.h> ------------------------- */
mod types {
use crate::{PamHandle, PamItemType, PamResult, PamReturnCode};
use libc::{c_int, c_void};
use pam_sys as ffi;
use std::ffi::{CStr, CString};
/// Update PAM information of type `item_type` in the associated PAM transaction
#[inline]
pub fn set_item(
handle: &mut PamHandle,
item_type: PamItemType,
item: &c_void,
) -> PamResult<()> {
match unsafe { ffi::pam_set_item(handle, item_type as c_int, item) }.into() {
PamReturnCode::Success => Ok(()),
err => Err(err.into()),
}
}
/// Retrieve PAM information of type `item_type` from the associated PAM transaction
#[inline]
pub fn get_item<'a>(handle: &PamHandle, item_type: PamItemType) -> PamResult<&'a c_void> {
let mut item_ptr: *const c_void = std::ptr::null();
match unsafe { ffi::pam_get_item(handle, item_type as c_int, &mut item_ptr) }.into() {
PamReturnCode::Success => {
assert!(
!item_ptr.is_null(),
"Got PAM_SUCCESS from pam_get_item, but ptr is null!"
);
Ok(unsafe { &*item_ptr })
}
err => Err(err.into()),
}
}
/// Retrieve a `CStr` describing the `PamReturnCode` passed, potentially
/// using LC_MESSAGES to localize the result
#[inline]
pub fn strerror(handle: &mut PamHandle, errnum: PamReturnCode) -> &str {
// We don't match here, as man says this function always returns a pointer to a string
unsafe { CStr::from_ptr(ffi::pam_strerror(handle, errnum as c_int)) }
.to_str()
.expect("Got invalid UTF8 string from pam_strerror")
}
/// Add or change PAM environment variables associated with the PAM transaction
#[inline]
pub fn putenv(handle: &mut PamHandle, name_value: &str) -> PamResult<()> {
if let Ok(name_value) = CString::new(name_value) {
match unsafe { ffi::pam_putenv(handle, name_value.as_ptr()) }.into() {
PamReturnCode::Success => Ok(()),
err => Err(err.into()),
}
} else {
super::buffer_error()
}
}
/// Get he value of a PAM environment variable associated with the PAM
/// transaction
#[inline]
pub fn getenv<'a>(handle: &'a mut PamHandle, name: &str) -> PamResult<Option<&'a str>> {
if let Ok(name) = CString::new(name) {
// Get environment variable
let env = unsafe { ffi::pam_getenv(handle, name.as_ptr()) };
if !env.is_null() {
// Convert to rust &str
Ok(Some(
unsafe { CStr::from_ptr(env) }
.to_str()
.expect("Got invalid UTF-8 string from pam_getenv"),
))
} else {
// This might still be an error, but we don't know for sure
Ok(None)
}
} else {
super::buffer_error()
}
}
// FIXME: Implement this properly
/*/// Retrieve a complee copy of the PAM environment associated with
/// the PAM transaction
#[inline]
pub fn getenvlist(handle: &mut PamHandle) -> *const *const c_char {
//TODO: find a convenient way to handle this with Rust types
unsafe { ffi::pam_getenvlist(handle) }
}*/
}
/* ----------------------- <security/_pam_types.h> ------------------------- */
/* ----------------------- <security/pam_misc.h> --------------------------- */
// FIXME: Investigate, if pam_misc is supported on any other platform
#[cfg(target_os = "freebsd")]
mod misc {
use crate::{PamHandle, PamResult, PamReturnCode};
use pam_sys as ffi;
use std::ffi::CString;
/// Update the PAM environment via the supplied list
#[inline]
pub fn misc_paste_env(handle: &mut PamHandle, user_env: &[&str]) -> PamResult<()> {
// Taken from: https://github.com/rust-lang/rust/issues/9564#issuecomment-95354558
let user_env: Vec<_> = user_env
.iter()
// FIXME: This panics if there are nul-bytes in any string
.map(|&env| CString::new(env).unwrap())
.collect();
let env_ptrs: Vec<_> = user_env
.iter()
.map(|env| env.as_ptr())
.chain(Some(std::ptr::null()))
.collect();
match unsafe { ffi::pam_misc_paste_env(handle, env_ptrs.as_ptr()) }.into() {
PamReturnCode::Success => Ok(()),
err => Err(err.into()),
}
}
// FIXME: implement this properly
/*/// Free memory of an environment list obtained via `getenvlist`
#[inline]
pub fn misc_drop_env(env: &mut *mut c_char) -> PamReturnCode {
unsafe { ffi::pam_misc_drop_env(env) })
}*/
/// Add or change PAM environment variables associated with the PAM transaction
/// in BSD style "name=value"
#[inline]
pub fn misc_setenv(
handle: &mut PamHandle,
name: &str,
value: &str,
readonly: bool,
) -> PamResult<()> {
if let (Ok(name), Ok(value)) = (CString::new(name), CString::new(value)) {
let flag = readonly as libc::c_int;
match unsafe { ffi::pam_misc_setenv(handle, name.as_ptr(), value.as_ptr(), flag) }
.into()
{
PamReturnCode::Success => Ok(()),
err => Err(err.into()),
}
} else {
super::buffer_error()
}
}
}
/* ----------------------- <security/pam_misc.h> --------------------------- */
/* ----------------------- <security/pam_modules.h> ------------------------ */
#[cfg(feature = "module")]
mod modules {
use crate::{PamHandle, PamResult, PamReturnCode};
use libc::{c_char, c_int, c_void};
use pam_sys as ffi;
use std::ffi::{CStr, CString};
/// Associate a pointer to an object with the given `module_data_name` in
/// the current PAM context
#[inline]
pub fn set_data(
handle: &mut PamHandle,
module_data_name: &str,
data: &mut c_void,
// FIXME: Remove bare ptrs from closure signature
cleanup: Option<unsafe extern "C" fn(*mut PamHandle, *mut c_void, c_int)>,
) -> PamResult<()> {
if let Ok(module_data_name) = CString::new(module_data_name) {
match unsafe { ffi::pam_set_data(handle, module_data_name.as_ptr(), data, cleanup) }
.into()
{
PamReturnCode::Success => Ok(()),
err => Err(err.into()),
}
} else {
super::buffer_error()
}
}
// FIXME: implement this properly
/*/// Retrieve the object associated with the given `module_data_name` from
/// the current PAM context
//pub fn get_data(handle: *const PamHandle, module_data_name: *const c_char, data: *const *const c_void);
*/
/// Return the name of the user as specified via `start`
#[inline]
pub fn get_user<'a>(handle: &'a PamHandle, prompt: Option<&str>) -> PamResult<&'a str> {
// For some reason, bindgen marks the handl as mutable in pam_sys although man says const
let handle = handle as *const PamHandle as *mut PamHandle;
let mut user_ptr: *const c_char = std::ptr::null();
let prompt_ptr = super::try_str_option_to_ptr(prompt)?;
match unsafe { ffi::pam_get_user(handle, &mut user_ptr, prompt_ptr) }.into() {
PamReturnCode::Success => {
assert!(
!user_ptr.is_null(),
"Got PAM_Success from pam_get_user but ptr is null!"
);
Ok(unsafe { CStr::from_ptr(user_ptr) }
.to_str()
.expect("Got invalid UTF8 string from pam_get_user"))
}
err => Err(err.into()),
}
}
}
/* ----------------------- <security/pam_modules.h> ------------------------ */
#[inline]
fn buffer_error<T>() -> crate::PamResult<T> {
Err(crate::PamReturnCode::Buf_Err.into())
}
fn try_str_option_to_ptr(opt: Option<&str>) -> crate::PamResult<*const libc::c_char> {
match opt.map(std::ffi::CString::new) {
// Valid string given -> Return ptr of the converted CString
Some(Ok(content)) => Ok(content.as_ptr()),
// No string given -> Return null-ptr
None => Ok(std::ptr::null_mut()),
// Invalid string given -> Return BUF_ERR
_ => Err(crate::PamReturnCode::Buf_Err.into()),
}
}