Skip to content

Commit 9a65753

Browse files
authored
Enforce that entry points cannot escape in the scripts directory (#19464)
For [GHSA-4gg8-gxpx-9rph](GHSA-4gg8-gxpx-9rph)
1 parent d77d849 commit 9a65753

4 files changed

Lines changed: 350 additions & 51 deletions

File tree

‎crates/uv-fs/src/path.rs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,21 @@ pub fn normalize_path<'path>(path: impl Into<Cow<'path, Path>>) -> Cow<'path, Pa
263263
path
264264
}
265265

266+
/// Normalize `path`, returning it when it remains strictly under a non-empty `root`.
267+
///
268+
/// This comparison is lexical and does not resolve symlinks. The returned path is normalized, and
269+
/// equality with `root` is rejected.
270+
pub fn normalize_path_under(path: impl AsRef<Path>, root: impl AsRef<Path>) -> Option<PathBuf> {
271+
let path = normalize_path(path.as_ref()).into_owned();
272+
let root = normalize_path(root.as_ref());
273+
274+
if root.as_os_str().is_empty() || path.as_path() == root.as_ref() {
275+
None
276+
} else {
277+
path.starts_with(root.as_ref()).then_some(path)
278+
}
279+
}
280+
266281
/// Normalize a [`Path`].
267282
///
268283
/// Unlike [`normalize_absolute_path`], this works with relative paths and does never error.
@@ -727,6 +742,32 @@ mod tests {
727742
}
728743
}
729744

745+
#[test]
746+
fn test_normalize_path_under() {
747+
assert_eq!(
748+
normalize_path_under("scripts/script", "scripts"),
749+
Some(PathBuf::from("scripts/script"))
750+
);
751+
assert_eq!(
752+
normalize_path_under("/scripts/script", "/scripts"),
753+
Some(PathBuf::from("/scripts/script"))
754+
);
755+
assert_eq!(
756+
normalize_path_under("scripts/nested/../script", "scripts"),
757+
Some(PathBuf::from("scripts/script"))
758+
);
759+
assert_eq!(
760+
normalize_path_under("/scripts/nested/../script", "/scripts"),
761+
Some(PathBuf::from("/scripts/script"))
762+
);
763+
assert_eq!(normalize_path_under("scripts/.", "scripts"), None);
764+
assert_eq!(normalize_path_under("/scripts/.", "/scripts"), None);
765+
assert_eq!(normalize_path_under("scripts/../script", "scripts"), None);
766+
assert_eq!(normalize_path_under("/scripts/../script", "/scripts"), None);
767+
assert_eq!(normalize_path_under("scripts/script", "."), None);
768+
assert_eq!(normalize_path_under("scripts/script", ""), None);
769+
}
770+
730771
#[test]
731772
fn test_normalize_trailing_path_separator() {
732773
let cases = [

‎crates/uv-install-wheel/src/lib.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ pub enum Error {
8686
InvalidEggLink(PathBuf),
8787
#[error(transparent)]
8888
LauncherError(#[from] uv_trampoline_builder::Error),
89-
#[error("Scripts must not use the reserved name {0}")]
90-
ReservedScriptName(String),
89+
#[error("Scripts must not use the reserved name `{reserved}`, got: `{declared}`")]
90+
ReservedScriptName { reserved: String, declared: String },
9191
#[error(transparent)]
9292
Copy(#[from] uv_fs::link::LinkError),
9393
}

‎crates/uv-install-wheel/src/wheel.rs‎

Lines changed: 87 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use sha2::{Digest, Sha256};
1414
use tracing::{debug, instrument, trace, warn};
1515
use walkdir::WalkDir;
1616

17-
use uv_fs::{PortablePath, Simplified, persist_with_retry_sync, relative_to};
17+
use uv_fs::{PortablePath, Simplified, normalize_path_under, persist_with_retry_sync, relative_to};
1818
use uv_normalize::PackageName;
1919
use uv_pypi_types::DirectUrl;
2020
use uv_shell::escape_posix_for_single_quotes;
@@ -160,69 +160,108 @@ fn get_script_executable(python_executable: &Path, is_gui: bool) -> PathBuf {
160160
}
161161
}
162162

163-
/// Determine the absolute path to an entrypoint script.
164-
fn entrypoint_path(entrypoint: &Script, layout: &Layout) -> PathBuf {
165-
if cfg!(windows) {
166-
// On windows we actually build an .exe wrapper
167-
let script_name = entrypoint
168-
.name
169-
// FIXME: What are the in-reality rules here for names?
170-
.strip_suffix(".py")
171-
.unwrap_or(&entrypoint.name)
172-
.to_string()
173-
+ ".exe";
174-
175-
layout.scheme.scripts.join(script_name)
176-
} else {
177-
layout.scheme.scripts.join(&entrypoint.name)
178-
}
163+
const RESERVED_SCRIPT_NAMES_ERROR: &[&str; 3] = &["python", "pythonw", "python3"];
164+
const RESERVED_SCRIPT_NAMES_WARN: &[&str; 2] = &["activate", "activate_this.py"];
165+
166+
/// A form of [`Script`] guaranteed by [`ValidatedScript::try_from_script`] to be constrained to
167+
/// the scripts directory.
168+
struct ValidatedScript<'script> {
169+
path: PathBuf,
170+
script: &'script Script,
179171
}
180172

181-
/// Create the wrapper scripts in the bin folder of the venv for launching console scripts.
182-
pub(crate) fn write_script_entrypoints(
183-
layout: &Layout,
184-
relocatable: bool,
185-
site_packages: &Path,
186-
entrypoints: &[Script],
187-
record: &mut Vec<RecordEntry>,
188-
is_gui: bool,
189-
) -> Result<(), Error> {
190-
for entrypoint in entrypoints {
191-
let warn_names = ["activate", "activate_this.py"];
192-
if warn_names.contains(&entrypoint.name.as_str())
193-
|| entrypoint.name.starts_with("activate.")
194-
{
173+
impl<'script> ValidatedScript<'script> {
174+
fn try_from_script(script: &'script Script, layout: &Layout) -> Result<Self, Error> {
175+
let Some(path) = normalize_path_under(
176+
layout.scheme.scripts.join(&script.name),
177+
&layout.scheme.scripts,
178+
) else {
179+
return Err(Error::InvalidWheel(format!(
180+
"Script path must resolve to a file within the scripts directory: `{}`",
181+
script.name
182+
)));
183+
};
184+
185+
let name = relative_to(&path, &layout.scheme.scripts)?
186+
.to_string_lossy()
187+
.into_owned();
188+
189+
if RESERVED_SCRIPT_NAMES_WARN.contains(&name.as_str()) || name.starts_with("activate.") {
195190
warn_user_once!(
196191
"The script name `{}` is reserved for virtual environment activation scripts.",
197-
entrypoint.name
192+
name
198193
);
199194
}
200-
let reserved_names = ["python", "pythonw", "python3"];
201-
if reserved_names.contains(&entrypoint.name.as_str())
202-
|| entrypoint
203-
.name
195+
196+
if RESERVED_SCRIPT_NAMES_ERROR.contains(&name.as_str())
197+
|| name
204198
.strip_prefix("python3.")
205199
.is_some_and(|suffix| suffix.parse::<u8>().is_ok())
206200
{
207-
return Err(Error::ReservedScriptName(entrypoint.name.clone()));
201+
return Err(Error::ReservedScriptName {
202+
reserved: name,
203+
declared: script.name.clone(),
204+
});
208205
}
209206

210-
let entrypoint_absolute = entrypoint_path(entrypoint, layout);
207+
let path = if cfg!(windows) {
208+
// On Windows we actually build an `.exe` wrapper.
209+
let name = name
210+
// FIXME: What are the in-reality rules here for names?
211+
.strip_suffix(".py")
212+
.unwrap_or(&name)
213+
.to_string()
214+
+ std::env::consts::EXE_SUFFIX;
211215

212-
let entrypoint_relative = pathdiff::diff_paths(&entrypoint_absolute, site_packages)
213-
.ok_or_else(|| {
214-
Error::Io(io::Error::other(format!(
215-
"Could not find relative path for: {}",
216-
entrypoint_absolute.simplified_display()
217-
)))
218-
})?;
216+
layout.scheme.scripts.join(name)
217+
} else {
218+
layout.scheme.scripts.join(name)
219+
};
220+
221+
Ok(Self { path, script })
222+
}
223+
224+
fn as_path(&self) -> &Path {
225+
&self.path
226+
}
227+
228+
fn inner(&self) -> &Script {
229+
self.script
230+
}
231+
232+
/// Return the script destination relative to `site_packages` for use in `RECORD`.
233+
///
234+
/// Entry points are installed in the scripts directory, which may sit outside
235+
/// `site_packages`, so we use a lexical diff rather than stripping a prefix.
236+
fn relative_to_site_package(&self, site_packages: &Path) -> Result<PathBuf, Error> {
237+
pathdiff::diff_paths(self.as_path(), site_packages).ok_or_else(|| {
238+
Error::Io(io::Error::other(format!(
239+
"Could not find relative path for: {}",
240+
self.as_path().simplified_display()
241+
)))
242+
})
243+
}
244+
}
245+
246+
/// Create the wrapper scripts in the bin folder of the venv for launching console scripts.
247+
pub(crate) fn write_script_entrypoints(
248+
layout: &Layout,
249+
relocatable: bool,
250+
site_packages: &Path,
251+
entrypoints: &[Script],
252+
record: &mut Vec<RecordEntry>,
253+
is_gui: bool,
254+
) -> Result<(), Error> {
255+
for script in entrypoints {
256+
let script = ValidatedScript::try_from_script(script, layout)?;
257+
let entrypoint_relative = script.relative_to_site_package(site_packages)?;
219258

220259
// Generate the launcher script.
221260
let launcher_executable = get_script_executable(&layout.sys_executable, is_gui);
222261
let launcher_executable =
223262
get_relocatable_executable(launcher_executable, layout, relocatable)?;
224263
let launcher_python_script = get_script_launcher(
225-
entrypoint,
264+
script.inner(),
226265
&format_shebang(&launcher_executable, &layout.os_name, relocatable),
227266
);
228267

@@ -248,8 +287,8 @@ pub(crate) fn write_script_entrypoints(
248287
use std::fs::Permissions;
249288
use std::os::unix::fs::PermissionsExt;
250289

251-
let path = site_packages.join(entrypoint_relative);
252-
let permissions = fs::metadata(&path)?.permissions();
290+
let path = script.as_path();
291+
let permissions = fs::metadata(path)?.permissions();
253292
if permissions.mode() & 0o111 != 0o111 {
254293
fs::set_permissions(path, Permissions::from_mode(permissions.mode() | 0o111))?;
255294
}

0 commit comments

Comments
 (0)