fix(content): validate provider download paths
This commit is contained in:
1 parent
fb976f1cb9
commit
95a25836a0
4 files changed
+177
-23
No files matched your search
@@ -2,7 +2,7 @@
|
|||||||
// and extract config/resource overrides from the zip
|
// and extract config/resource overrides from the zip
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::Path;
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
@@ -223,31 +223,39 @@ async fn download_mod_files(
|
|||||||
for _ in 0..max_concurrent {
|
for _ in 0..max_concurrent {
|
||||||
if let Some(file) = file_iter.next() {
|
if let Some(file) = file_iter.next() {
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let dest = minecraft_dir.join(&file.path);
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
let dest = minecraft_dir.join(relative);
|
||||||
if url.is_empty() {
|
let url = file.downloads.first().cloned().ok_or_else(|| {
|
||||||
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
|
crate::net::NetError::Parse(format!(
|
||||||
}
|
".mrpack file '{}' has no download URL",
|
||||||
|
file.path
|
||||||
|
))
|
||||||
|
})?;
|
||||||
let filename = file
|
let filename = file
|
||||||
.path
|
.path
|
||||||
.rsplit('/')
|
.rsplit('/')
|
||||||
.next()
|
.next()
|
||||||
.unwrap_or(&file.path)
|
.unwrap_or(&file.path)
|
||||||
.to_string();
|
.to_string();
|
||||||
|
let hashes = file.hashes.clone();
|
||||||
|
let file_size = file.file_size;
|
||||||
let completed = completed.clone();
|
let completed = completed.clone();
|
||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
if let Some(parent) = dest.parent()
|
if let Some(parent) = dest.parent()
|
||||||
&& let Err(e) = tokio::fs::create_dir_all(parent).await
|
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||||
{
|
{
|
||||||
tracing::warn!(
|
return Err(crate::net::NetError::from(error));
|
||||||
"Failed to create mod download directory {}: {}",
|
|
||||||
parent.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
progress::set_sub_action(filename);
|
progress::set_sub_action(filename);
|
||||||
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
||||||
|
if !verify_mrpack_file(&dest, file_size, &hashes)? {
|
||||||
|
let _ = tokio::fs::remove_file(&dest).await;
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Downloaded .mrpack file '{}' failed its size or hash verification",
|
||||||
|
dest.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||||
Ok::<(), crate::net::NetError>(())
|
Ok::<(), crate::net::NetError>(())
|
||||||
@@ -262,31 +270,36 @@ async fn download_mod_files(
|
|||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||||
}
|
}
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let dest = minecraft_dir.join(&file.path);
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
let dest = minecraft_dir.join(relative);
|
||||||
if url.is_empty() {
|
let url = file.downloads.first().cloned().ok_or_else(|| {
|
||||||
tracing::warn!(".mrpack file '{}' has no download URL", file.path);
|
crate::net::NetError::Parse(format!(".mrpack file '{}' has no download URL", file.path))
|
||||||
}
|
})?;
|
||||||
let filename = file
|
let filename = file
|
||||||
.path
|
.path
|
||||||
.rsplit('/')
|
.rsplit('/')
|
||||||
.next()
|
.next()
|
||||||
.unwrap_or(&file.path)
|
.unwrap_or(&file.path)
|
||||||
.to_string();
|
.to_string();
|
||||||
|
let hashes = file.hashes.clone();
|
||||||
|
let file_size = file.file_size;
|
||||||
let completed = completed.clone();
|
let completed = completed.clone();
|
||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
if let Some(parent) = dest.parent()
|
if let Some(parent) = dest.parent()
|
||||||
&& let Err(e) = tokio::fs::create_dir_all(parent).await
|
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||||
{
|
{
|
||||||
tracing::warn!(
|
return Err(crate::net::NetError::from(error));
|
||||||
"Failed to create mod download directory {}: {}",
|
|
||||||
parent.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
progress::set_sub_action(filename);
|
progress::set_sub_action(filename);
|
||||||
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
||||||
|
if !verify_mrpack_file(&dest, file_size, &hashes)? {
|
||||||
|
let _ = tokio::fs::remove_file(&dest).await;
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Downloaded .mrpack file '{}' failed its size or hash verification",
|
||||||
|
dest.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||||
Ok::<(), crate::net::NetError>(())
|
Ok::<(), crate::net::NetError>(())
|
||||||
@@ -302,6 +315,39 @@ async fn download_mod_files(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
|
||||||
|
let path = Path::new(path);
|
||||||
|
if path.as_os_str().is_empty()
|
||||||
|
|| path
|
||||||
|
.components()
|
||||||
|
.any(|component| !matches!(component, std::path::Component::Normal(_)))
|
||||||
|
{
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Unsafe .mrpack file path '{}'",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(path.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_mrpack_file(
|
||||||
|
path: &Path,
|
||||||
|
expected_size: u64,
|
||||||
|
expected_hashes: &HashMap<String, String>,
|
||||||
|
) -> Result<bool, crate::net::NetError> {
|
||||||
|
let fingerprint = fingerprint(path)?;
|
||||||
|
if fingerprint.size != expected_size {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(["sha512", "sha1"].into_iter().all(|algorithm| {
|
||||||
|
expected_hashes.get(algorithm).is_none_or(|expected| {
|
||||||
|
fingerprint
|
||||||
|
.hash(algorithm)
|
||||||
|
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
fn seed_content_manifest(
|
fn seed_content_manifest(
|
||||||
index: &MrpackIndex,
|
index: &MrpackIndex,
|
||||||
paths: &InstancePaths,
|
paths: &InstancePaths,
|
||||||
|
|||||||
@@ -217,6 +217,72 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mod_file_rejects_paths_outside_the_instance() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
let index = MrpackIndex {
|
||||||
|
format_version: 1,
|
||||||
|
game: "minecraft".to_owned(),
|
||||||
|
version_id: "1".to_owned(),
|
||||||
|
name: "Unsafe path".to_owned(),
|
||||||
|
dependencies: Default::default(),
|
||||||
|
files: vec![MrpackFile {
|
||||||
|
path: "../escape.jar".to_owned(),
|
||||||
|
hashes: Default::default(),
|
||||||
|
downloads: vec!["https://example.invalid/escape.jar".to_owned()],
|
||||||
|
file_size: 1,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
let error = download_mod_files(&index, tmp.path()).await.unwrap_err();
|
||||||
|
|
||||||
|
assert!(error.to_string().contains("Unsafe .mrpack file path"));
|
||||||
|
assert!(!tmp.path().parent().unwrap().join("escape.jar").exists());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mod_file_removes_downloads_with_invalid_metadata() {
|
||||||
|
let _guard = crate::tests::TEST_LOCK
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|error| error.into_inner());
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(method("GET"))
|
||||||
|
.and(path("/corrupt.jar"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"corrupt".to_vec()))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let index = MrpackIndex {
|
||||||
|
format_version: 1,
|
||||||
|
game: "minecraft".to_owned(),
|
||||||
|
version_id: "1".to_owned(),
|
||||||
|
name: "Corrupt download".to_owned(),
|
||||||
|
dependencies: Default::default(),
|
||||||
|
files: vec![MrpackFile {
|
||||||
|
path: "mods/corrupt.jar".to_owned(),
|
||||||
|
hashes: Default::default(),
|
||||||
|
downloads: vec![format!("{}/corrupt.jar", server.uri())],
|
||||||
|
file_size: 1,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
assert!(download_mod_files(&index, tmp.path()).await.is_err());
|
||||||
|
assert!(!tmp.path().join("mods/corrupt.jar").exists());
|
||||||
|
crate::feedback::progress::clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn import_seeds_exact_modrinth_content_identity() {
|
fn import_seeds_exact_modrinth_content_identity() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -389,6 +389,8 @@ pub async fn download_version_file(
|
|||||||
destination: &std::path::Path,
|
destination: &std::path::Path,
|
||||||
) -> Result<DownloadOutcome, crate::net::NetError> {
|
) -> Result<DownloadOutcome, crate::net::NetError> {
|
||||||
let file = select_primary_file(version)?;
|
let file = select_primary_file(version)?;
|
||||||
|
validate_path_component(&file.filename, "provider filename")?;
|
||||||
|
validate_path_component(&version.id, "provider version id")?;
|
||||||
let path = destination.join(&file.filename);
|
let path = destination.join(&file.filename);
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
if verify_version_file(&path, file)? {
|
if verify_version_file(&path, file)? {
|
||||||
@@ -428,6 +430,8 @@ pub async fn download_version_file_for_update(
|
|||||||
installed_path: &std::path::Path,
|
installed_path: &std::path::Path,
|
||||||
) -> Result<DownloadOutcome, crate::net::NetError> {
|
) -> Result<DownloadOutcome, crate::net::NetError> {
|
||||||
let file = select_primary_file(version)?;
|
let file = select_primary_file(version)?;
|
||||||
|
validate_path_component(&file.filename, "provider filename")?;
|
||||||
|
validate_path_component(&version.id, "provider version id")?;
|
||||||
let target = destination.join(&file.filename);
|
let target = destination.join(&file.filename);
|
||||||
if target != installed_path {
|
if target != installed_path {
|
||||||
return download_version_file(client, version, destination).await;
|
return download_version_file(client, version, destination).await;
|
||||||
@@ -464,6 +468,18 @@ pub async fn download_version_file_for_update(
|
|||||||
Ok(DownloadOutcome::Downloaded(target))
|
Ok(DownloadOutcome::Downloaded(target))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn validate_path_component(value: &str, label: &str) -> Result<(), crate::net::NetError> {
|
||||||
|
let mut components = std::path::Path::new(value).components();
|
||||||
|
if !matches!(components.next(), Some(std::path::Component::Normal(_)))
|
||||||
|
|| components.next().is_some()
|
||||||
|
{
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Invalid {label} '{value}'"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn verify_version_file(
|
fn verify_version_file(
|
||||||
path: &std::path::Path,
|
path: &std::path::Path,
|
||||||
expected: &VersionFile,
|
expected: &VersionFile,
|
||||||
|
|||||||
@@ -207,6 +207,32 @@ async fn content_download_skips_an_existing_filename() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn content_download_rejects_provider_path_components() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let version = version_with_files(vec![VersionFile {
|
||||||
|
url: "https://example.test/escape.jar".to_owned(),
|
||||||
|
filename: "../escape.jar".to_owned(),
|
||||||
|
size: 1,
|
||||||
|
primary: true,
|
||||||
|
hashes: HashMap::new(),
|
||||||
|
}]);
|
||||||
|
|
||||||
|
let error = download_version_file(&crate::net::HttpClient::new(), &version, directory.path())
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
|
||||||
|
assert!(error.to_string().contains("Invalid provider filename"));
|
||||||
|
assert!(
|
||||||
|
!directory
|
||||||
|
.path()
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.join("escape.jar")
|
||||||
|
.exists()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
|
async fn staged_update_replaces_the_old_file_and_cleans_its_backup() {
|
||||||
let directory = tempfile::tempdir().unwrap();
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
Reference in new issue
Block a user