Debian Codegraph @

src/sudoers/policy.rs

raw symbols SCIP
1 //! Data types and traits that represent what the "terms and conditions" are after a successful
2 //! permission check.
3 //!
4 //! The trait definitions can be part of some global crate in the future, if we support more
5 //! than just the sudoers file.
6
7 use super::{Judgement, Sudoers};
8 use crate::common::{
9 HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2, SudoPath,
10 };
11 use crate::exec::Umask;
12 use crate::sudoers::ast::{ExecControl, Tag};
13 use crate::system::{Hostname, User};
14 use std::collections::HashSet;
15 use std::time::Duration;
16 use std::{ffi::OsString, path::PathBuf};
17
18 #[must_use]
19 #[cfg_attr(test, derive(Debug, PartialEq))]
20 #[repr(u32)]
21 pub enum Authorization<T = ()> {
22 Allowed(Authentication, T) = HARDENED_ENUM_VALUE_0,
23 Forbidden = HARDENED_ENUM_VALUE_1,
24 }
25
26 #[cfg_attr(test, derive(Debug, PartialEq))]
27 #[must_use]
28 pub struct Authentication {
29 pub must_authenticate: bool,
30 pub credential: AuthenticatingUser,
31 pub allowed_attempts: u16,
32 pub prior_validity: Duration,
33 pub pwfeedback: bool,
34 pub password_timeout: Option<Duration>,
35 pub noninteractive_auth: bool,
36 }
37
38 impl super::Settings {
39 pub(super) fn to_auth(&self, tag: &Tag) -> Authentication {
40 Authentication {
41 must_authenticate: tag.needs_passwd(),
42 allowed_attempts: self.passwd_tries().try_into().unwrap(),
43 prior_validity: Duration::from_secs(self.timestamp_timeout()),
44 pwfeedback: self.pwfeedback(),
45 password_timeout: match self.passwd_timeout() {
46 0 => None,
47 timeout => Some(Duration::from_secs(timeout)),
48 },
49 noninteractive_auth: self.noninteractive_auth(),
50 credential: if self.rootpw() {
51 AuthenticatingUser::Root
52 } else if self.targetpw() {
53 AuthenticatingUser::TargetUser
54 } else {
55 AuthenticatingUser::InvokingUser
56 },
57 }
58 }
59 }
60
61 #[must_use]
62 #[cfg_attr(test, derive(Debug, PartialEq))]
63 pub struct Restrictions<'a> {
64 pub use_pty: bool,
65 pub trust_environment: bool,
66 pub noexec: bool,
67 pub env_keep: &'a HashSet<String>,
68 pub env_check: &'a HashSet<String>,
69 pub chdir: DirChange,
70 pub path: Option<&'a str>,
71 pub umask: Umask,
72 #[cfg(feature = "apparmor")]
73 pub apparmor_profile: Option<String>,
74 }
75
76 #[must_use]
77 #[cfg_attr(test, derive(Debug, PartialEq))]
78 #[repr(u32)]
79 pub enum DirChange {
80 Strict(Option<SudoPath>) = HARDENED_ENUM_VALUE_0,
81 Any = HARDENED_ENUM_VALUE_1,
82 }
83
84 #[cfg_attr(test, derive(Debug, PartialEq))]
85 #[repr(u32)]
86 pub enum AuthenticatingUser {
87 InvokingUser = HARDENED_ENUM_VALUE_0,
88 Root = HARDENED_ENUM_VALUE_1,
89 TargetUser = HARDENED_ENUM_VALUE_2,
90 }
91
92 impl Judgement {
93 pub fn authorization(&self) -> Authorization<Restrictions<'_>> {
94 // NOTE: we should add conditional compilation to the DSL; this avoids getting
95 // an unused warning message
96 #[cfg(not(feature = "apparmor"))]
97 let _ = &self.settings.apparmor_profile();
98
99 if let Some(tag) = &self.flags {
100 Authorization::Allowed(
101 self.settings.to_auth(tag),
102 Restrictions {
103 use_pty: self.settings.use_pty(),
104 trust_environment: match tag.env {
105 super::EnvironmentControl::Implicit => self.settings.setenv(),
106 super::EnvironmentControl::Setenv => true,
107 super::EnvironmentControl::Nosetenv => false,
108 },
109 noexec: match tag.noexec {
110 ExecControl::Implicit => self.settings.noexec(),
111 ExecControl::Exec => false,
112 ExecControl::Noexec => true,
113 },
114 env_keep: self.settings.env_keep(),
115 env_check: self.settings.env_check(),
116 chdir: match tag.cwd.clone().or_else(|| {
117 // a `runcwd` default acts as the working directory when no explicit CWD was set
118 self.settings
119 .runcwd()
120 .and_then(|s| super::basic_parser::Token::construct(s.to_string()).ok())
121 }) {
122 None => DirChange::Strict(None),
123 Some(super::ChDir::Any) => DirChange::Any,
124 Some(super::ChDir::Path(path)) => DirChange::Strict(Some(path)),
125 },
126 path: self.settings.secure_path(),
127 umask: {
128 let mask = self
129 .settings
130 .umask()
131 .try_into()
132 .expect("the umask parser should have prevented overflow");
133 if mask == 0o777 {
134 Umask::Preserve
135 } else if self.settings.umask_override() {
136 Umask::Override(mask)
137 } else {
138 Umask::Extend(mask)
139 }
140 },
141 #[cfg(feature = "apparmor")]
142 apparmor_profile: tag
143 .apparmor_profile
144 .as_deref()
145 .or(self.settings.apparmor_profile())
146 .map(|x| x.to_string()),
147 },
148 )
149 } else {
150 Authorization::Forbidden
151 }
152 }
153
154 pub(crate) fn preferred_editor(&self) -> (PathBuf, Vec<OsString>) {
155 // if no editor could be selected, fall back to /bin/vi;
156 // note that /bin/vi is also likely to have been tried as part of
157 // the "editor" setting, so this is a last-resort
158 super::select_editor(&self.settings, true)
159 .unwrap_or_else(|| (std::path::PathBuf::from("/usr/bin/vi"), vec![]))
160 }
161 }
162
163 impl Sudoers {
164 pub fn search_path(
165 &mut self,
166 on_host: &Hostname,
167 current_user: &User,
168 target_user: &User,
169 ) -> Option<&str> {
170 self.specify_host_user_runas(on_host, current_user, Some(target_user));
171 self.settings.secure_path()
172 }
173 }
174
175 #[cfg(test)]
176 mod test {
177 use super::*;
178 use crate::sudoers::{
179 ast::{Authenticate, Tag},
180 tokens::ChDir,
181 };
182
183 impl Judgement {
184 fn mod_flag(&mut self, mut modify: impl FnMut(&mut Tag)) {
185 let mut tag: Tag = self.flags.clone().unwrap_or_default();
186 modify(&mut tag);
187 self.flags = Some(tag);
188 }
189 }
190
191 #[test]
192 fn authority_xlat_test() {
193 let mut judge: Judgement = Default::default();
194 assert_eq!(judge.authorization(), Authorization::Forbidden);
195 judge.mod_flag(|tag| tag.authenticate = Authenticate::Passwd);
196 let Authorization::Allowed(auth, restrictions) = judge.authorization() else {
197 panic!();
198 };
199 assert_eq!(
200 auth,
201 Authentication {
202 must_authenticate: true,
203 allowed_attempts: 3,
204 prior_validity: Duration::from_secs(15 * 60),
205 credential: AuthenticatingUser::InvokingUser,
206 pwfeedback: true,
207 noninteractive_auth: false,
208 password_timeout: Some(Duration::from_secs(300)),
209 },
210 );
211
212 let mut judge = judge.clone();
213 judge.mod_flag(|tag| tag.authenticate = Authenticate::Nopasswd);
214 let Authorization::Allowed(auth, restrictions2) = judge.authorization() else {
215 panic!();
216 };
217 assert_eq!(
218 auth,
219 Authentication {
220 must_authenticate: false,
221 allowed_attempts: 3,
222 prior_validity: Duration::from_secs(15 * 60),
223 credential: AuthenticatingUser::InvokingUser,
224 pwfeedback: true,
225 noninteractive_auth: false,
226 password_timeout: Some(Duration::from_secs(300)),
227 },
228 );
229 assert_eq!(restrictions, restrictions2);
230 }
231
232 #[test]
233 fn chdir_test() {
234 let mut judge = Judgement {
235 flags: Some(Tag::default()),
236 ..Default::default()
237 };
238 fn chdir(judge: &mut Judgement) -> DirChange {
239 let Authorization::Allowed(_, ctl) = judge.authorization() else {
240 panic!()
241 };
242 ctl.chdir
243 }
244 assert_eq!(chdir(&mut judge), DirChange::Strict(None));
245 judge.mod_flag(|tag| tag.cwd = Some(ChDir::Any));
246 assert_eq!(chdir(&mut judge), DirChange::Any);
247 judge.mod_flag(|tag| tag.cwd = Some(ChDir::Path("/usr".into())));
248 assert_eq!(chdir(&mut judge), (DirChange::Strict(Some("/usr".into()))));
249 judge.mod_flag(|tag| tag.cwd = Some(ChDir::Path("/bin".into())));
250 assert_eq!(chdir(&mut judge), (DirChange::Strict(Some("/bin".into()))));
251 }
252 }