Debian Codegraph @

libs/gst/helpers/ptp/privileges.rs

raw
1 // GStreamer
2 //
3 // Copyright (C) 2015-2023 Sebastian Dröge <[email protected]>
4 //
5 // This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
6 // If a copy of the MPL was not distributed with this file, You can obtain one at
7 // <https://mozilla.org/MPL/2.0/>.
8 //
9 // SPDX-License-Identifier: MPL-2.0
10
11 use crate::error::Error;
12
13 #[cfg(ptp_helper_permissions = "setcap")]
14 mod setcap {
15 use super::*;
16
17 use crate::{error::Context, ffi::unix::setcaps::*};
18 use std::io;
19
20 struct Cap(cap_t);
21
22 impl Drop for Cap {
23 fn drop(&mut self) {
24 // SAFETY: The capabilities are valid by construction and are only dropped
25 // once here.
26 unsafe {
27 let _ = cap_free(self.0);
28 }
29 }
30 }
31
32 impl Cap {
33 /// Get the current process' capabilities.
34 fn get_proc() -> io::Result<Self> {
35 // SAFETY: Get the current capabilities of the process. This returns NULL on error or
36 // otherwise newly allocated capabilities that have to be freed again in the end. For
37 // that purpose we wrap them in the Cap struct.
38 unsafe {
39 let c = cap_get_proc();
40 if c.is_null() {
41 return Err(io::Error::last_os_error());
42 }
43
44 Ok(Cap(c))
45 }
46 }
47
48 /// Clear all capabilities.
49 fn clear(&mut self) -> io::Result<()> {
50 // SAFETY: Clearing all current capabilities. This requires a valid capabilities
51 // pointer, which we have at this point by construction.
52 unsafe {
53 if cap_clear(self.0) != 0 {
54 return Err(io::Error::last_os_error());
55 }
56 }
57
58 Ok(())
59 }
60
61 /// Set current process' capabilities.
62 fn set_proc(&self) -> io::Result<()> {
63 // SAFETY: Setting the current process's capabilities, which is only affecting the
64 // current thread unfortunately. At this point, no other threads were started yet so
65 // this is not a problem. Also the capabilities pointer is still valid by construction.
66 unsafe {
67 if cap_set_proc(self.0) != 0 {
68 return Err(io::Error::last_os_error());
69 }
70 }
71 Ok(())
72 }
73 }
74
75 /// Drop all current capabilities of the process.
76 pub fn drop() -> Result<(), Error> {
77 let mut c = Cap::get_proc().context("Failed to get current process capabilities")?;
78 c.clear().context("Failed to clear capabilities")?;
79 c.set_proc()
80 .context("Failed to set current process capabilities")?;
81
82 Ok(())
83 }
84
85 #[cfg(test)]
86 mod test {
87 #[test]
88 fn test_get_set_same_and_clear_cap() {
89 let mut c = super::Cap::get_proc().unwrap();
90 // Setting the same capabilities should always succeed
91 c.set_proc().unwrap();
92 c.clear().unwrap();
93 }
94 }
95 }
96
97 #[cfg(ptp_helper_permissions = "setuid-root")]
98 mod setuid_root {
99 use super::*;
100
101 use crate::{bail, error::Context, ffi::unix::setuid_root::*};
102 use std::{ffi::CString, io};
103
104 /// Retrieve UID and GID for the given username.
105 fn get_uid_gid_for_user(name: &str) -> io::Result<(uid_t, gid_t)> {
106 let name_cstr = CString::new(name).unwrap();
107
108 loop {
109 // SAFETY: getpwnam() requires a NUL-terminated user name string and
110 // returns either the user information in static storage, or NULL on error.
111 // In case of EINTR, getting the user information can be retried.
112 //
113 // The user information is stored in static storage so might change if something
114 // else calls related functions. As this is the only thread up to this point and we
115 // just extract two integers from it there is no such possibility.
116 unsafe {
117 let pw = getpwnam(name_cstr.as_ptr());
118 if pw.is_null() {
119 let err = io::Error::last_os_error();
120 if err.kind() == io::ErrorKind::Interrupted {
121 continue;
122 }
123 if err.raw_os_error() == Some(0) {
124 return Err(io::Error::from(io::ErrorKind::NotFound));
125 }
126
127 return Err(err);
128 }
129 return Ok(((*pw).pw_uid, (*pw).pw_gid));
130 }
131 }
132 }
133
134 /// Retrieve GID for the given group name.
135 fn get_gid_for_group(name: &str) -> io::Result<gid_t> {
136 let name_cstr = CString::new(name).unwrap();
137 loop {
138 // SAFETY: getgrnam() requires a NUL-terminated group name string and
139 // returns either the group information in static storage, or NULL on error.
140 // In case of EINTR, getting the group information can be retried.
141 //
142 // The user information is stored in static storage so might change if something
143 // else calls related functions. As this is the only thread up to this point and we
144 // just extract two integers from it there is no such possibility.
145 unsafe {
146 let grp = getgrnam(name_cstr.as_ptr());
147 if grp.is_null() {
148 let err = io::Error::last_os_error();
149 if err.kind() == io::ErrorKind::Interrupted {
150 continue;
151 }
152 if err.raw_os_error() == Some(0) {
153 return Err(io::Error::from(io::ErrorKind::NotFound));
154 }
155
156 return Err(err);
157 }
158
159 return Ok((*grp).gr_gid);
160 }
161 }
162 }
163
164 #[cfg(test)]
165 mod test {
166 #[test]
167 fn test_get_uid_gid_for_user() {
168 match super::get_uid_gid_for_user("root") {
169 Ok(_) => (),
170 Err(err) if err.kind() != std::io::ErrorKind::NotFound => {
171 panic!("{}", err);
172 }
173 _ => (),
174 }
175 }
176
177 #[test]
178 fn test_get_gid_for_group() {
179 match super::get_gid_for_group("root") {
180 Ok(_) => (),
181 Err(err) if err.kind() != std::io::ErrorKind::NotFound => {
182 panic!("{}", err);
183 }
184 _ => (),
185 }
186 }
187 }
188
189 /// Drop the process's UID/GID from root to the configured user/group or the user "nobody".
190 pub fn drop() -> Result<(), Error> {
191 let username = gst_ptp_helper_conf::PTP_HELPER_SETUID_USER.unwrap_or("nobody");
192
193 let (uid, gid) = get_uid_gid_for_user(username)
194 .with_context(|| format!("Failed to get user information for {}", username))?;
195 let gid = if let Some(group) = gst_ptp_helper_conf::PTP_HELPER_SETUID_GROUP {
196 get_gid_for_group(group)
197 .with_context(|| format!("Failed to get group information for {}", group))?
198 } else {
199 gid
200 };
201
202 // SAFETY: This function can be called at any time and never fails.
203 let old_gid = unsafe { getgid() };
204
205 // SAFETY: Changes the effective group id of the process and return zero on success.
206 unsafe {
207 if setgid(gid) != 0 {
208 bail!(
209 source: io::Error::last_os_error(),
210 "Failed to set group id {} for process",
211 gid,
212 );
213 }
214 }
215
216 // SAFETY: Changes the effective user id of the process and return zero on success.
217 // On errors, try resetting to the old gid just to be sure.
218 unsafe {
219 if setuid(uid) != 0 {
220 let err = io::Error::last_os_error();
221 let _ = setgid(old_gid);
222 bail!(source: err, "Failed to set user id {} for process", uid);
223 }
224 }
225
226 Ok(())
227 }
228 }
229
230 /// Drop all additional permissions / capabilities the current process might have as they're not
231 /// needed anymore.
232 ///
233 /// This does nothing if no such mechanism is implemented / selected for the target platform.
234 pub fn drop() -> Result<(), Error> {
235 #[cfg(ptp_helper_permissions = "setcap")]
236 {
237 setcap::drop()?;
238 }
239 #[cfg(ptp_helper_permissions = "setuid-root")]
240 {
241 setuid_root::drop()?;
242 }
243
244 Ok(())
245 }