Debian Codegraph @

src/sudoers/entry.rs

raw symbols SCIP
1 use core::fmt;
2
3 use crate::sudoers::{
4 VecOrd,
5 ast::{Identifier, Qualified, UserSpecifier},
6 tokens::{ChDir, Meta},
7 };
8 use crate::{
9 common::{DisplayOsStr, SudoString, resolve::CurrentUser},
10 system::{User, interface::UserId},
11 };
12
13 use self::verbose::Verbose;
14
15 use super::{
16 ast::{Authenticate, Def, EnvironmentControl, ExecControl, RunAs, Tag},
17 tokens::{Args, Command},
18 };
19
20 mod verbose;
21
22 pub struct Entry<'a> {
23 run_as: Option<&'a RunAs>,
24 cmd_specs: Vec<(Tag, &'a Qualified<Meta<Command>>)>,
25 cmd_alias: &'a VecOrd<Def<Command>>,
26 }
27
28 impl<'a> Entry<'a> {
29 pub(super) fn new(
30 run_as: Option<&'a RunAs>,
31 cmd_specs: Vec<(Tag, &'a Qualified<Meta<Command>>)>,
32 cmd_alias: &'a VecOrd<Def<Command>>,
33 ) -> Self {
34 debug_assert!(!cmd_specs.is_empty());
35
36 Self {
37 run_as,
38 cmd_specs,
39 cmd_alias,
40 }
41 }
42
43 pub fn verbose(self) -> impl fmt::Display + 'a {
44 Verbose(self)
45 }
46 }
47
48 fn root_runas() -> RunAs {
49 let name = User::from_uid(UserId::ROOT)
50 .ok()
51 .flatten()
52 .map(|u| u.name)
53 .unwrap_or(SudoString::new("root".into()).unwrap());
54
55 let name = UserSpecifier::User(Identifier::Name(name));
56 let name = Qualified::Allow(Meta::Only(name));
57
58 RunAs {
59 users: vec![name],
60 groups: vec![],
61 }
62 }
63
64 impl fmt::Display for Entry<'_> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 let Self {
67 run_as,
68 cmd_specs,
69 cmd_alias,
70 } = self;
71
72 let root_runas = root_runas();
73 let run_as = run_as.unwrap_or(&root_runas);
74
75 f.write_str(" (")?;
76 write_users(run_as, f)?;
77 if !run_as.groups.is_empty() {
78 f.write_str(" : ")?;
79 }
80 write_groups(run_as, f)?;
81 f.write_str(") ")?;
82
83 let mut last_tag = None;
84 for (tag, spec) in cmd_specs {
85 let is_first_iteration = last_tag.is_none();
86
87 if !is_first_iteration {
88 f.write_str(", ")?;
89 }
90
91 write_tag(f, tag, &mut last_tag, spec)?;
92
93 // cmd_alias is to be topologically sorted (dependencies come before dependents),
94 // the argument to write_spec needs to have dependents before dependencies.
95 write_spec(f, spec, cmd_alias.iter().rev(), true, ", ")?;
96 }
97
98 Ok(())
99 }
100 }
101
102 fn write_users(run_as: &RunAs, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
103 if run_as.users.is_empty() {
104 match CurrentUser::resolve() {
105 Ok(u) => f.write_str(&u.name)?,
106 _ => f.write_str("?")?,
107 };
108 }
109
110 let mut is_first_user = true;
111 for user in &run_as.users {
112 if !is_first_user {
113 f.write_str(", ")?;
114 }
115 is_first_user = false;
116
117 let meta = match user {
118 Qualified::Allow(meta) => meta,
119 Qualified::Forbid(meta) => {
120 f.write_str("!")?;
121 meta
122 }
123 };
124
125 match meta {
126 Meta::All => f.write_str("ALL")?,
127 Meta::Only(user) => {
128 let ident = match user {
129 UserSpecifier::User(ident) => ident,
130 UserSpecifier::Group(ident) => {
131 f.write_str("%")?;
132 ident
133 }
134 UserSpecifier::NonunixGroup(ident) => {
135 f.write_str("%:")?;
136 ident
137 }
138 };
139
140 match ident {
141 Identifier::Name(name) => f.write_str(name)?,
142 Identifier::ID(id) => write!(f, "#{id}")?,
143 }
144 }
145 Meta::Alias(alias) => f.write_str(alias)?,
146 }
147 }
148
149 Ok(())
150 }
151
152 fn write_groups(run_as: &RunAs, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
153 let mut is_first_group = true;
154 for group in &run_as.groups {
155 if !is_first_group {
156 f.write_str(", ")?;
157 }
158 is_first_group = false;
159
160 let meta = match group {
161 Qualified::Allow(meta) => meta,
162 Qualified::Forbid(meta) => {
163 f.write_str("!")?;
164 meta
165 }
166 };
167
168 match meta {
169 Meta::All => f.write_str("ALL")?,
170 Meta::Only(ident) => match ident {
171 Identifier::Name(name) => f.write_str(name)?,
172 Identifier::ID(id) => write!(f, "#{id}")?,
173 },
174 Meta::Alias(alias) => f.write_str(alias)?,
175 }
176 }
177
178 Ok(())
179 }
180
181 fn write_tag(
182 f: &mut fmt::Formatter,
183 tag: &Tag,
184 last_tag: &mut Option<Tag>,
185 spec: &Qualified<Meta<Command>>,
186 ) -> fmt::Result {
187 let last_tag = last_tag.get_or_insert(Tag::default());
188
189 if tag.apparmor_profile != last_tag.apparmor_profile {
190 f.write_str("APPARMOR_PROFILE=")?;
191 let profile = tag
192 .apparmor_profile
193 .as_ref()
194 .expect("sudoers spec turned off");
195 f.write_str(profile)?;
196 f.write_str(" ")?;
197 }
198
199 if tag.cwd != last_tag.cwd {
200 f.write_str("CWD=")?;
201 match tag.cwd.as_ref().expect("sudoers spec turned off") {
202 ChDir::Path(path) => write!(f, "{}", path.display())?,
203 ChDir::Any => f.write_str("*")?,
204 }
205 f.write_str(" ")?;
206 }
207
208 let mut write_tag = |text, status: bool| {
209 if !status {
210 f.write_str("NO")?;
211 };
212 f.write_str(text)?;
213 f.write_str(": ")
214 };
215
216 if tag.env != last_tag.env
217 && !(matches!(spec, Qualified::Allow(Meta::All)) && tag.env == EnvironmentControl::Setenv)
218 {
219 write_tag("SETENV", tag.env == EnvironmentControl::Setenv)?;
220 }
221 if tag.noexec != last_tag.noexec {
222 write_tag("EXEC", tag.noexec == ExecControl::Exec)?;
223 }
224 if tag.authenticate != last_tag.authenticate {
225 write_tag("PASSWD", tag.authenticate != Authenticate::Nopasswd)?;
226 }
227
228 *last_tag = tag.clone();
229 Ok(())
230 }
231
232 fn write_spec<'a>(
233 f: &mut fmt::Formatter,
234 spec: &Qualified<Meta<Command>>,
235 mut alias_list: impl Iterator<Item = &'a Def<Command>> + Clone,
236 mut sign: bool,
237 separator: &str,
238 ) -> fmt::Result {
239 let meta = match spec {
240 Qualified::Allow(meta) => meta,
241 Qualified::Forbid(meta) => {
242 sign = !sign;
243 meta
244 }
245 };
246
247 match meta {
248 Meta::All | Meta::Only(_) if !sign => f.write_str("!")?,
249 _ => {}
250 }
251
252 match meta {
253 Meta::All => f.write_str("ALL")?,
254
255 Meta::Only((cmd, args)) => {
256 write!(f, "{cmd}")?;
257 match args {
258 Args::Exact(args) => {
259 for arg in args {
260 write!(f, " {}", DisplayOsStr(arg))?;
261 }
262 if args.is_empty() {
263 write!(f, " \"\"")?;
264 }
265 }
266 Args::Prefix(args) => {
267 for arg in args {
268 write!(f, " {}", DisplayOsStr(arg))?;
269 }
270 if !args.is_empty() {
271 write!(f, " *")?;
272 }
273 }
274 }
275 }
276 Meta::Alias(alias) => {
277 if let Some(Def(_, spec_list)) = alias_list.find(|Def(id, _)| id == alias) {
278 let mut is_first_iteration = true;
279 for spec in spec_list {
280 if !is_first_iteration {
281 f.write_str(separator)?;
282 }
283 // 1) this recursion will terminate, since "alias_list" has become smaller
284 // by the "alias_list.find()" above
285 // 2) to get the correct macro expansion, alias_list has to be (reverse-)topologically
286 // sorted so that "later" definitions do not refer back to "earlier" definitions.
287 write_spec(f, spec, alias_list.clone(), sign, separator)?;
288 is_first_iteration = false;
289 }
290 } else {
291 f.write_str("???")?
292 }
293 }
294 }
295
296 Ok(())
297 }