diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index cead526..00964f8 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -2,7 +2,7 @@ // and extract config/resource overrides from the zip use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use serde::Deserialize; @@ -223,31 +223,39 @@ async fn download_mod_files( for _ in 0..max_concurrent { if let Some(file) = file_iter.next() { let client = client.clone(); - let dest = minecraft_dir.join(&file.path); - let url = file.downloads.first().cloned().unwrap_or_default(); - if url.is_empty() { - tracing::warn!(".mrpack file '{}' has no download URL", file.path); - } + let relative = safe_mrpack_path(&file.path)?; + let dest = minecraft_dir.join(relative); + let url = file.downloads.first().cloned().ok_or_else(|| { + crate::net::NetError::Parse(format!( + ".mrpack file '{}' has no download URL", + file.path + )) + })?; let filename = file .path .rsplit('/') .next() .unwrap_or(&file.path) .to_string(); + let hashes = file.hashes.clone(); + let file_size = file.file_size; let completed = completed.clone(); tasks.spawn(async move { 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!( - "Failed to create mod download directory {}: {}", - parent.display(), - e - ); + return Err(crate::net::NetError::from(error)); } progress::set_sub_action(filename); tracing::trace!("Downloading .mrpack file to {}", dest.display()); 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; progress::set_action(format!("Downloading mods... {done}/{total}")); Ok::<(), crate::net::NetError>(()) @@ -262,31 +270,36 @@ async fn download_mod_files( .map_err(|e| -> Box { Box::new(e) })?; } let client = client.clone(); - let dest = minecraft_dir.join(&file.path); - let url = file.downloads.first().cloned().unwrap_or_default(); - if url.is_empty() { - tracing::warn!(".mrpack file '{}' has no download URL", file.path); - } + let relative = safe_mrpack_path(&file.path)?; + let dest = minecraft_dir.join(relative); + let url = file.downloads.first().cloned().ok_or_else(|| { + crate::net::NetError::Parse(format!(".mrpack file '{}' has no download URL", file.path)) + })?; let filename = file .path .rsplit('/') .next() .unwrap_or(&file.path) .to_string(); + let hashes = file.hashes.clone(); + let file_size = file.file_size; let completed = completed.clone(); tasks.spawn(async move { 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!( - "Failed to create mod download directory {}: {}", - parent.display(), - e - ); + return Err(crate::net::NetError::from(error)); } progress::set_sub_action(filename); tracing::trace!("Downloading .mrpack file to {}", dest.display()); 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; progress::set_action(format!("Downloading mods... {done}/{total}")); Ok::<(), crate::net::NetError>(()) @@ -302,6 +315,39 @@ async fn download_mod_files( Ok(()) } +fn safe_mrpack_path(path: &str) -> Result { + 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, +) -> Result { + 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( index: &MrpackIndex, paths: &InstancePaths, diff --git a/src/instance/tests/import/mrpack.rs b/src/instance/tests/import/mrpack.rs index 60b7798..4400291 100644 --- a/src/instance/tests/import/mrpack.rs +++ b/src/instance/tests/import/mrpack.rs @@ -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] fn import_seeds_exact_modrinth_content_identity() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/net/modrinth.rs b/src/net/modrinth.rs index 9d7b7b6..4800364 100644 --- a/src/net/modrinth.rs +++ b/src/net/modrinth.rs @@ -389,6 +389,8 @@ pub async fn download_version_file( destination: &std::path::Path, ) -> Result { 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); if path.exists() { if verify_version_file(&path, file)? { @@ -428,6 +430,8 @@ pub async fn download_version_file_for_update( installed_path: &std::path::Path, ) -> Result { 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); if target != installed_path { return download_version_file(client, version, destination).await; @@ -464,6 +468,18 @@ pub async fn download_version_file_for_update( 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( path: &std::path::Path, expected: &VersionFile, diff --git a/src/net/tests/modrinth.rs b/src/net/tests/modrinth.rs index 2828b91..9a20776 100644 --- a/src/net/tests/modrinth.rs +++ b/src/net/tests/modrinth.rs @@ -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] async fn staged_update_replaces_the_old_file_and_cleans_its_backup() { let directory = tempfile::tempdir().unwrap();