Debian Codegraph @

src/sudo/pipeline.rs

raw symbols SCIP
1 use std::ffi::OsStr;
2 use std::time::Duration;
3
4 use super::cli::{SudoRunOptions, SudoValidateOptions};
5 use super::diagnostic;
6 use crate::common::resolve::{AuthUser, CurrentUser};
7 use crate::common::{Context, Error};
8 use crate::log::{auth_info, auth_warn};
9 use crate::pam::PamContext;
10 use crate::sudo::env::environment;
11 use crate::sudo::pam::{InitPamArgs, attempt_authenticate, init_pam, pre_exec};
12 use crate::sudoers::{AuthenticatingUser, Authentication, Authorization, Judgement, Sudoers};
13 use crate::system::term::current_tty_name;
14 use crate::system::timestamp::{RecordScope, SessionRecordFile, TouchResult};
15 use crate::system::{Process, escape_os_str_lossy};
16
17 mod list;
18 pub(super) use list::run_list;
19
20 mod edit;
21 pub(super) use edit::run_edit;
22
23 fn read_sudoers() -> Result<Sudoers, Error> {
24 let sudoers_path = &super::candidate_sudoers_file();
25
26 let (sudoers, syntax_errors) = Sudoers::open(sudoers_path).map_err(|e| {
27 // Provide a more helpful error message when the sudoers file is missing
28 if e.kind() == std::io::ErrorKind::NotFound {
29 Error::Configuration(xlat!(
30 "sudoers file not found: {path}\n\
31 \n\
32 The sudoers file is required for sudo-rs to function. Please ensure:\n\
33 - The file exists at the expected location\n\
34 - You have the necessary permissions to read it\n\
35 - If setting up sudo-rs for the first time, create a sudoers file with appropriate permissions\n\
36 \n\
37 For more information, see the sudo-rs documentation.",
38 path = sudoers_path.display()
39 ))
40 } else {
41 Error::Configuration(xlat!("invalid configuration: {error}", error = e))
42 }
43 })?;
44
45 for crate::sudoers::Error {
46 source,
47 location,
48 message,
49 } in syntax_errors
50 {
51 let path = source.as_deref().unwrap_or(sudoers_path);
52 diagnostic::diagnostic!("{message}", path @ location);
53 }
54
55 Ok(sudoers)
56 }
57
58 fn judge(mut policy: Sudoers, context: &Context) -> Result<Judgement, Error> {
59 Ok(policy.check(
60 &*context.current_user,
61 &context.hostname,
62 crate::sudoers::Request {
63 user: &context.target_user,
64 group: &context.target_group,
65 command: &context.command.command,
66 arguments: &context.command.arguments,
67 },
68 ))
69 }
70
71 pub fn run(mut cmd_opts: SudoRunOptions) -> Result<(), Error> {
72 let mut policy = read_sudoers()?;
73
74 let user_requested_env_vars = std::mem::take(&mut cmd_opts.env_var_list);
75
76 let context = Context::from_run_opts(cmd_opts, &mut policy)?;
77
78 let policy = judge(policy, &context)?;
79
80 let Authorization::Allowed(auth, controls) = policy.authorization() else {
81 return Err(Error::Authorization(context.current_user.name.to_string()));
82 };
83
84 let mut pam_context = auth_and_update_record_file(&context, auth)?;
85
86 // build environment
87 let additional_env = pre_exec(&mut pam_context, &context.target_user.name)?;
88
89 let current_env = environment::system_environment();
90 let (checked_vars, trusted_vars) = if controls.trust_environment {
91 (vec![], user_requested_env_vars)
92 } else {
93 (user_requested_env_vars, vec![])
94 };
95
96 let mut target_env = environment::get_target_environment(
97 current_env,
98 additional_env,
99 checked_vars,
100 &context,
101 &controls,
102 )?;
103
104 environment::dangerous_extend(&mut target_env, trusted_vars);
105
106 // prepare switch of apparmor profile
107 #[cfg(feature = "apparmor")]
108 if let Some(profile) = &controls.apparmor_profile {
109 crate::apparmor::set_profile_for_next_exec(profile)
110 .map_err(|err| Error::AppArmor(profile.clone(), err))?;
111 }
112
113 let options = context.try_as_run_options(&controls)?;
114
115 // Log after try_as_run_options to avoid logging if the command is not resolved
116 log_command_execution(&context);
117
118 // run command and return corresponding exit code
119 let command_exit_reason = crate::exec::run_command(options, target_env)
120 .map_err(|io_error| Error::Io(Some(context.command.command), io_error));
121
122 pam_context.close_session();
123
124 match command_exit_reason?.exit_process()? {}
125 }
126
127 pub fn run_validate(cmd_opts: SudoValidateOptions) -> Result<(), Error> {
128 let mut policy = read_sudoers()?;
129
130 let context = Context::from_validate_opts(cmd_opts)?;
131
132 match policy.check_validate_permission(&*context.current_user, &context.hostname) {
133 Authorization::Forbidden => {
134 return Err(Error::Authorization(context.current_user.name.to_string()));
135 }
136 Authorization::Allowed(auth, ()) => {
137 auth_and_update_record_file(&context, auth)?;
138 }
139 }
140
141 Ok(())
142 }
143
144 fn auth_and_update_record_file(
145 context: &Context,
146 Authentication {
147 must_authenticate,
148 prior_validity,
149 allowed_attempts,
150 password_timeout,
151 ref credential,
152 pwfeedback,
153 noninteractive_auth,
154 }: Authentication,
155 ) -> Result<PamContext, Error> {
156 let auth_user = match credential {
157 AuthenticatingUser::InvokingUser => {
158 AuthUser::from_current_user(context.current_user.clone())
159 }
160 AuthenticatingUser::Root => AuthUser::resolve_root_for_rootpw()?,
161 AuthenticatingUser::TargetUser => {
162 AuthUser::from_user_for_targetpw(context.target_user.clone())
163 }
164 };
165
166 let scope = RecordScope::for_process(&Process::new());
167 let mut auth_status = determine_auth_status(
168 must_authenticate,
169 context.use_session_records,
170 scope,
171 &context.current_user,
172 &auth_user,
173 prior_validity,
174 );
175
176 let mut pam_context = init_pam(InitPamArgs {
177 launch: context.launch,
178 use_askpass: context.askpass,
179 use_stdin: context.stdin,
180 bell: context.bell,
181 non_interactive: context.non_interactive,
182 password_feedback: pwfeedback,
183 password_timeout,
184 auth_prompt: context.prompt.clone(),
185 auth_user: &auth_user.name,
186 requesting_user: &context.current_user.name,
187 target_user: &context.target_user.name,
188 hostname: &context.hostname,
189 })?;
190 if auth_status.must_authenticate {
191 if context.non_interactive && !noninteractive_auth {
192 return Err(Error::InteractionRequired);
193 }
194
195 attempt_authenticate(
196 &mut pam_context,
197 &auth_user.name,
198 context.non_interactive,
199 allowed_attempts,
200 )?;
201 if let (Some(record_file), Some(scope)) = (&mut auth_status.record_file, scope) {
202 match record_file.create(scope, &auth_user) {
203 Ok(_) => (),
204 Err(e) => {
205 auth_warn!("Could not update session record file with new record: {e}");
206 }
207 }
208 }
209 }
210
211 pam_context.validate_account_or_change_auth_token()?;
212
213 Ok(pam_context)
214 }
215
216 /// This should determine what the authentication status for the given record
217 /// match limit and origin/target user from the context is.
218 fn determine_auth_status(
219 must_policy_authenticate: bool,
220 use_session_records: bool,
221 record_for: Option<RecordScope>,
222 current_user: &CurrentUser,
223 auth_user: &AuthUser,
224 prior_validity: Duration,
225 ) -> AuthStatus {
226 if !must_policy_authenticate {
227 AuthStatus::new(false, None)
228 } else if let (true, Some(record_for)) = (use_session_records, record_for) {
229 match SessionRecordFile::open_for_user(current_user, prior_validity) {
230 Ok(mut sr) => {
231 match sr.touch(record_for, auth_user) {
232 // if a record was found and updated within the timeout, we do not need to authenticate
233 Ok(TouchResult::Updated { .. }) => AuthStatus::new(false, Some(sr)),
234 Ok(TouchResult::NotFound | TouchResult::Outdated { .. }) => {
235 AuthStatus::new(true, Some(sr))
236 }
237 Err(e) => {
238 auth_warn!("Unexpected error while reading session information: {e}");
239 AuthStatus::new(true, None)
240 }
241 }
242 }
243 // if we cannot open the session record file we just assume there is none and continue as normal
244 Err(e) => {
245 auth_warn!("Could not use session information: {e}");
246 AuthStatus::new(true, None)
247 }
248 }
249 } else {
250 AuthStatus::new(true, None)
251 }
252 }
253
254 struct AuthStatus {
255 must_authenticate: bool,
256 record_file: Option<SessionRecordFile>,
257 }
258
259 impl AuthStatus {
260 fn new(must_authenticate: bool, record_file: Option<SessionRecordFile>) -> AuthStatus {
261 AuthStatus {
262 must_authenticate,
263 record_file,
264 }
265 }
266 }
267
268 fn log_command_execution(context: &Context) {
269 let tty_info = if let Ok(tty_name) = current_tty_name() {
270 format!("TTY={} ;", escape_os_str_lossy(&tty_name))
271 } else {
272 String::from("")
273 };
274 let pwd = escape_os_str_lossy(
275 std::env::current_dir()
276 .as_ref()
277 .map(|s| s.as_os_str())
278 .unwrap_or_else(|_| OsStr::new("unknown")),
279 );
280 let user = context.target_user.name.escape_debug().collect::<String>();
281 auth_info!(
282 "{} : {} PWD={} ; USER={} ; COMMAND={}",
283 &context.current_user.name,
284 tty_info,
285 pwd,
286 user,
287 &context.command
288 );
289 }