comparison pam/src/module.rs @ 44:50371046c61a default tip

Add support for pam_get_authtok and minor cleanups. This change adds the pam_get_authtok function for PAM modules, as well as performing a few cleanups: - Pattern match in a few more places. - Pull out string-copying into a function. - Format and run clippy. - Replace outdated PAM doc links with man7.org pages.
author Paul Fisher <paul@pfish.zone>
date Sat, 08 Mar 2025 19:29:46 -0500
parents ec70822cbdef
children
comparison
equal deleted inserted replaced
43:60e74d6a2b88 44:50371046c61a
2 2
3 use libc::c_char; 3 use libc::c_char;
4 use std::ffi::{CStr, CString}; 4 use std::ffi::{CStr, CString};
5 5
6 use constants::{PamFlag, PamResultCode}; 6 use constants::{PamFlag, PamResultCode};
7 use items::ItemType;
7 8
8 /// Opaque type, used as a pointer when making pam API calls. 9 /// Opaque type, used as a pointer when making pam API calls.
9 /// 10 ///
10 /// A module is invoked via an external function such as `pam_sm_authenticate`. 11 /// A module is invoked via an external function such as `pam_sm_authenticate`.
11 /// Such a call provides a pam handle pointer. The same pointer should be given 12 /// Such a call provides a pam handle pointer. The same pointer should be given
34 ), 35 ),
35 ) -> PamResultCode; 36 ) -> PamResultCode;
36 37
37 fn pam_get_item( 38 fn pam_get_item(
38 pamh: *const PamHandle, 39 pamh: *const PamHandle,
39 item_type: crate::items::ItemType, 40 item_type: ItemType,
40 item: &mut *const libc::c_void, 41 item: &mut *const libc::c_void,
41 ) -> PamResultCode; 42 ) -> PamResultCode;
42 43
43 fn pam_set_item( 44 fn pam_set_item(
44 pamh: *mut PamHandle, 45 pamh: *mut PamHandle,
45 item_type: crate::items::ItemType, 46 item_type: ItemType,
46 item: *const libc::c_void, 47 item: *const libc::c_void,
47 ) -> PamResultCode; 48 ) -> PamResultCode;
48 49
49 fn pam_get_user( 50 fn pam_get_user(
50 pamh: *const PamHandle, 51 pamh: *const PamHandle,
51 user: &*mut c_char, 52 user: &*mut c_char,
52 prompt: *const c_char, 53 prompt: *const c_char,
53 ) -> PamResultCode; 54 ) -> PamResultCode;
55
56 fn pam_get_authtok(
57 pamh: *const PamHandle,
58 item_type: ItemType,
59 data: &*mut c_char,
60 prompt: *const c_char,
61 ) -> PamResultCode;
62
54 } 63 }
55 64
56 pub extern "C" fn cleanup<T>(_: *const PamHandle, c_data: *mut libc::c_void, _: PamResultCode) { 65 pub extern "C" fn cleanup<T>(_: *const PamHandle, c_data: *mut libc::c_void, _: PamResultCode) {
57 unsafe { 66 unsafe {
58 let _data: Box<T> = Box::from_raw(c_data.cast::<T>()); 67 let _data: Box<T> = Box::from_raw(c_data.cast::<T>());
63 72
64 impl PamHandle { 73 impl PamHandle {
65 /// Gets some value, identified by `key`, that has been set by the module 74 /// Gets some value, identified by `key`, that has been set by the module
66 /// previously. 75 /// previously.
67 /// 76 ///
68 /// See `pam_get_data` in 77 /// See the [`pam_get_data` manual page](
69 /// http://www.linux-pam.org/Linux-PAM-html/mwg-expected-by-module-item.html 78 /// https://www.man7.org/linux/man-pages/man3/pam_get_data.3.html).
70 /// 79 ///
71 /// # Errors 80 /// # Errors
72 /// 81 ///
73 /// Returns an error if the underlying PAM function call fails. 82 /// Returns an error if the underlying PAM function call fails.
74 /// 83 ///
75 /// # Safety 84 /// # Safety
76 /// 85 ///
77 /// The data stored under the provided key must be of type `T` otherwise the 86 /// The data stored under the provided key must be of type `T` otherwise the
78 /// behaviour of this funtion is undefined. 87 /// behaviour of this function is undefined.
79 pub unsafe fn get_data<'a, T>(&'a self, key: &str) -> PamResult<&'a T> { 88 pub unsafe fn get_data<T>(&self, key: &str) -> PamResult<&T> {
80 let c_key = CString::new(key).unwrap(); 89 let c_key = CString::new(key).unwrap();
81 let mut ptr: *const libc::c_void = std::ptr::null(); 90 let mut ptr: *const libc::c_void = std::ptr::null();
82 let res = pam_get_data(self, c_key.as_ptr(), &mut ptr); 91 let res = pam_get_data(self, c_key.as_ptr(), &mut ptr);
83 if PamResultCode::PAM_SUCCESS == res && !ptr.is_null() { 92 if PamResultCode::PAM_SUCCESS == res && !ptr.is_null() {
84 let typed_ptr = ptr.cast::<T>(); 93 let typed_ptr = ptr.cast::<T>();
90 } 99 }
91 100
92 /// Stores a value that can be retrieved later with `get_data`. The value lives 101 /// Stores a value that can be retrieved later with `get_data`. The value lives
93 /// as long as the current pam cycle. 102 /// as long as the current pam cycle.
94 /// 103 ///
95 /// See `pam_set_data` in 104 /// See the [`pam_set_data` manual page](
96 /// http://www.linux-pam.org/Linux-PAM-html/mwg-expected-by-module-item.html 105 /// https://www.man7.org/linux/man-pages/man3/pam_set_data.3.html).
97 /// 106 ///
98 /// # Errors 107 /// # Errors
99 /// 108 ///
100 /// Returns an error if the underlying PAM function call fails. 109 /// Returns an error if the underlying PAM function call fails.
101 pub fn set_data<T>(&self, key: &str, data: Box<T>) -> PamResult<()> { 110 pub fn set_data<T>(&self, key: &str, data: Box<T>) -> PamResult<()> {
106 c_key.as_ptr(), 115 c_key.as_ptr(),
107 Box::into_raw(data).cast::<libc::c_void>(), 116 Box::into_raw(data).cast::<libc::c_void>(),
108 cleanup::<T>, 117 cleanup::<T>,
109 ) 118 )
110 }; 119 };
111 if PamResultCode::PAM_SUCCESS == res { 120 to_result(res)
112 Ok(())
113 } else {
114 Err(res)
115 }
116 } 121 }
117 122
118 /// Retrieves a value that has been set, possibly by the pam client. This is 123 /// Retrieves a value that has been set, possibly by the pam client. This is
119 /// particularly useful for getting a `PamConv` reference. 124 /// particularly useful for getting a `PamConv` reference.
120 /// 125 ///
121 /// See `pam_get_item` in 126 /// See the [`pam_get_item` manual page](
122 /// http://www.linux-pam.org/Linux-PAM-html/mwg-expected-by-module-item.html 127 /// https://www.man7.org/linux/man-pages/man3/pam_get_item.3.html).
123 /// 128 ///
124 /// # Errors 129 /// # Errors
125 /// 130 ///
126 /// Returns an error if the underlying PAM function call fails. 131 /// Returns an error if the underlying PAM function call fails.
127 pub fn get_item<T: crate::items::Item>(&self) -> PamResult<Option<T>> { 132 pub fn get_item<T: crate::items::Item>(&self) -> PamResult<Option<T>> {
134 } else { 139 } else {
135 Some(T::from_raw(typed_ptr)) 140 Some(T::from_raw(typed_ptr))
136 }; 141 };
137 (r, t) 142 (r, t)
138 }; 143 };
139 if PamResultCode::PAM_SUCCESS == res { 144 match res {
140 Ok(item) 145 PamResultCode::PAM_SUCCESS => Ok(item),
141 } else { 146 other => Err(other),
142 Err(res)
143 } 147 }
144 } 148 }
145 149
146 /// Sets a value in the pam context. The value can be retrieved using 150 /// Sets a value in the pam context. The value can be retrieved using
147 /// `get_item`. 151 /// `get_item`.
148 /// 152 ///
149 /// Note that all items are strings, except `PAM_CONV` and `PAM_FAIL_DELAY`. 153 /// Note that all items are strings, except `PAM_CONV` and `PAM_FAIL_DELAY`.
150 /// 154 ///
151 /// See `pam_set_item` in 155 /// See the [`pam_set_item` manual page](
152 /// http://www.linux-pam.org/Linux-PAM-html/mwg-expected-by-module-item.html 156 /// https://www.man7.org/linux/man-pages/man3/pam_set_item.3.html).
153 /// 157 ///
154 /// # Errors 158 /// # Errors
155 /// 159 ///
156 /// Returns an error if the underlying PAM function call fails. 160 /// Returns an error if the underlying PAM function call fails.
157 /// 161 ///
158 /// # Panics 162 /// # Panics
159 /// 163 ///
160 /// Panics if the provided item key contains a nul byte 164 /// Panics if the provided item key contains a nul byte.
161 pub fn set_item_str<T: crate::items::Item>(&mut self, item: T) -> PamResult<()> { 165 pub fn set_item_str<T: crate::items::Item>(&mut self, item: T) -> PamResult<()> {
162 let res = 166 let res =
163 unsafe { pam_set_item(self, T::type_id(), item.into_raw().cast::<libc::c_void>())}; 167 unsafe { pam_set_item(self, T::type_id(), item.into_raw().cast::<libc::c_void>()) };
164 if PamResultCode::PAM_SUCCESS == res { 168 to_result(res)
165 Ok(())
166 } else {
167 Err(res)
168 }
169 } 169 }
170 170
171 /// Retrieves the name of the user who is authenticating or logging in. 171 /// Retrieves the name of the user who is authenticating or logging in.
172 /// 172 ///
173 /// This is really a specialization of `get_item`. 173 /// This is really a specialization of `get_item`.
174 /// 174 ///
175 /// See `pam_get_user` in 175 /// See the [`pam_get_user` manual page](
176 /// http://www.linux-pam.org/Linux-PAM-html/mwg-expected-by-module-item.html 176 /// https://www.man7.org/linux/man-pages/man3/pam_get_user.3.html).
177 /// 177 ///
178 /// # Errors 178 /// # Errors
179 /// 179 ///
180 /// Returns an error if the underlying PAM function call fails. 180 /// Returns an error if the underlying PAM function call fails.
181 /// 181 ///
182 /// # Panics 182 /// # Panics
183 /// 183 ///
184 /// Panics if the provided prompt string contains a nul byte 184 /// Panics if the provided prompt string contains a nul byte.
185 pub fn get_user(&self, prompt: Option<&str>) -> PamResult<String> { 185 pub fn get_user(&self, prompt: Option<&str>) -> PamResult<String> {
186 let ptr: *mut c_char = std::ptr::null_mut();
187 let prompt_string; 186 let prompt_string;
188 let c_prompt = match prompt { 187 let c_prompt = match prompt {
189 Some(p) => { 188 Some(p) => {
190 prompt_string = CString::new(p).unwrap(); 189 prompt_string = CString::new(p).unwrap();
191 prompt_string.as_ptr() 190 prompt_string.as_ptr()
192 } 191 }
193 None => std::ptr::null(), 192 None => std::ptr::null(),
194 }; 193 };
195 let res = unsafe { pam_get_user(self, &ptr, c_prompt) }; 194 let output: *mut c_char = std::ptr::null_mut();
196 if PamResultCode::PAM_SUCCESS == res && !ptr.is_null() { 195 let res = unsafe { pam_get_user(self, &output, c_prompt) };
197 let const_ptr = ptr as *const c_char; 196 match res {
198 let bytes = unsafe { CStr::from_ptr(const_ptr).to_bytes() }; 197 PamResultCode::PAM_SUCCESS => copy_pam_string(output),
199 String::from_utf8(bytes.to_vec()).map_err(|_| PamResultCode::PAM_CONV_ERR) 198 otherwise => Err(otherwise),
200 } else {
201 Err(res)
202 } 199 }
200 }
201
202 /// Retrieves the authentication token from the user.
203 ///
204 /// This is really a specialization of `get_item`.
205 ///
206 /// See the [`pam_get_authtok` manual page](
207 /// https://www.man7.org/linux/man-pages/man3/pam_get_authtok.3.html).
208 ///
209 /// # Errors
210 ///
211 /// Returns an error if the underlying PAM function call fails.
212 ///
213 /// # Panics
214 ///
215 /// Panics if the provided prompt string contains a nul byte.
216 pub fn get_authtok(&self, prompt: Option<&str>) -> PamResult<String> {
217 let prompt_string;
218 let c_prompt = match prompt {
219 Some(p) => {
220 prompt_string = CString::new(p).unwrap();
221 prompt_string.as_ptr()
222 }
223 None => std::ptr::null(),
224 };
225 let output: *mut c_char = std::ptr::null_mut();
226 let res = unsafe { pam_get_authtok(self, ItemType::AuthTok, &output, c_prompt) };
227 match res {
228 PamResultCode::PAM_SUCCESS => copy_pam_string(output),
229 otherwise => Err(otherwise),
230 }
231 }
232 }
233
234 /// Creates an owned copy of a string that is returned from a
235 /// <code>pam_get_<var>whatever</var></code> function.
236 fn copy_pam_string(result_ptr: *const c_char) -> PamResult<String> {
237 // We really shouldn't get a null pointer back here, but if we do, return nothing.
238 if result_ptr.is_null() {
239 return Ok(String::from(""));
240 }
241 let bytes = unsafe { CStr::from_ptr(result_ptr).to_bytes() };
242 String::from_utf8(bytes.to_vec()).map_err(|_| PamResultCode::PAM_CONV_ERR)
243 }
244
245 /// Convenience to transform a `PamResultCode` into a unit `PamResult`.
246 fn to_result(result: PamResultCode) -> PamResult<()> {
247 match result {
248 PamResultCode::PAM_SUCCESS => Ok(()),
249 otherwise => Err(otherwise),
203 } 250 }
204 } 251 }
205 252
206 /// Provides functions that are invoked by the entrypoints generated by the 253 /// Provides functions that are invoked by the entrypoints generated by the
207 /// [`pam_hooks!` macro](../macro.pam_hooks.html). 254 /// [`pam_hooks!` macro](../macro.pam_hooks.html).
208 /// 255 ///
209 /// All of hooks are ignored by PAM dispatch by default given the default return value of `PAM_IGNORE`. 256 /// All hooks are ignored by PAM dispatch by default given the default return value of `PAM_IGNORE`.
210 /// Override any functions that you want to handle with your module. See `man pam(3)`. 257 /// Override any functions that you want to handle with your module. See `man pam(3)`.
211 #[allow(unused_variables)] 258 #[allow(unused_variables)]
212 pub trait PamHooks { 259 pub trait PamHooks {
213 /// This function performs the task of establishing whether the user is permitted to gain access at 260 /// This function performs the task of establishing whether the user is permitted to gain access at
214 /// this time. It should be understood that the user has previously been validated by an 261 /// this time. It should be understood that the user has previously been validated by an