| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
use std::io::{Cursor, Read}; |
| 22 |
|
| 23 |
use crate::constants; |
| 24 |
use crate::storage::FileType; |
| 25 |
|
| 26 |
use super::{ErrorPolicy, LayerResult, LayerVerdict}; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
pub const ERROR_POLICY: ErrorPolicy = ErrorPolicy::FailClosed; |
| 32 |
|
| 33 |
|
| 34 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 35 |
enum ArchiveKind { |
| 36 |
Zip, |
| 37 |
Gzip, |
| 38 |
Bzip2, |
| 39 |
Xz, |
| 40 |
Zstd, |
| 41 |
} |
| 42 |
|
| 43 |
impl ArchiveKind { |
| 44 |
fn label(self) -> &'static str { |
| 45 |
match self { |
| 46 |
ArchiveKind::Zip => "ZIP", |
| 47 |
ArchiveKind::Gzip => "gzip", |
| 48 |
ArchiveKind::Bzip2 => "bzip2", |
| 49 |
ArchiveKind::Xz => "xz", |
| 50 |
ArchiveKind::Zstd => "zstd", |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
fn detect_kind(magic: &[u8]) -> Option<ArchiveKind> { |
| 59 |
match magic { |
| 60 |
[0x50, 0x4B, 0x03, 0x04, ..] => Some(ArchiveKind::Zip), |
| 61 |
[0x1F, 0x8B, ..] => Some(ArchiveKind::Gzip), |
| 62 |
[0x42, 0x5A, 0x68, ..] => Some(ArchiveKind::Bzip2), |
| 63 |
[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00, ..] => Some(ArchiveKind::Xz), |
| 64 |
[0x28, 0xB5, 0x2F, 0xFD, ..] => Some(ArchiveKind::Zstd), |
| 65 |
_ => None, |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
fn detect_unsupported_container(data: &[u8]) -> Option<&'static str> { |
| 84 |
|
| 85 |
const SEVENZ: &[u8] = &[0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C]; |
| 86 |
|
| 87 |
const RAR: &[u8] = &[0x52, 0x61, 0x72, 0x21, 0x1A, 0x07]; |
| 88 |
if contains_window(data, SEVENZ) { |
| 89 |
Some("7z") |
| 90 |
} else if contains_window(data, RAR) { |
| 91 |
Some("RAR") |
| 92 |
} else { |
| 93 |
None |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
fn contains_window(haystack: &[u8], needle: &[u8]) -> bool { |
| 99 |
haystack.windows(needle.len()).any(|w| w == needle) |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
fn has_zip_eocd(data: &[u8]) -> bool { |
| 107 |
const EOCD: [u8; 4] = [0x50, 0x4B, 0x05, 0x06]; |
| 108 |
|
| 109 |
let window = 22 + u16::MAX as usize; |
| 110 |
let start = data.len().saturating_sub(window); |
| 111 |
data[start..].windows(EOCD.len()).any(|w| w == EOCD) |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
pub fn check_archive_safety(data: &[u8], file_type: FileType) -> LayerResult { |
| 117 |
inspect_archive(data, file_type, None).0 |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
enum ContentBuf { |
| 122 |
|
| 123 |
Buffered(Vec<u8>), |
| 124 |
|
| 125 |
Overflow, |
| 126 |
|
| 127 |
BudgetExceeded, |
| 128 |
} |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
fn entry_bomb_stop_limit(compressed_size: u64) -> u64 { |
| 136 |
if compressed_size == 0 { |
| 137 |
return constants::SCAN_ZIP_MAX_UNCOMPRESSED; |
| 138 |
} |
| 139 |
let ratio_limit = compressed_size.saturating_mul(constants::SCAN_ZIP_MAX_RATIO as u64); |
| 140 |
constants::SCAN_ZIP_MAX_UNCOMPRESSED.min(ratio_limit) |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
fn tee_decompress( |
| 153 |
reader: &mut dyn Read, |
| 154 |
bomb_abs_limit: u64, |
| 155 |
want_content: bool, |
| 156 |
budget: &mut u64, |
| 157 |
) -> Result<(u64, Option<ContentBuf>), (u64, String)> { |
| 158 |
let mut counted: u64 = 0; |
| 159 |
let mut buf = [0u8; 8192]; |
| 160 |
let mut content = if want_content { |
| 161 |
Some(ContentBuf::Buffered(Vec::new())) |
| 162 |
} else { |
| 163 |
None |
| 164 |
}; |
| 165 |
loop { |
| 166 |
match reader.read(&mut buf) { |
| 167 |
Ok(0) => break, |
| 168 |
Ok(n) => { |
| 169 |
counted += n as u64; |
| 170 |
if let Some(ContentBuf::Buffered(ref mut v)) = content { |
| 171 |
if v.len() + n > INTERIOR_ENTRY_MAX { |
| 172 |
content = Some(ContentBuf::Overflow); |
| 173 |
} else if (n as u64) > *budget { |
| 174 |
content = Some(ContentBuf::BudgetExceeded); |
| 175 |
} else { |
| 176 |
*budget -= n as u64; |
| 177 |
v.extend_from_slice(&buf[..n]); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
|
| 182 |
if counted > bomb_abs_limit && !matches!(content, Some(ContentBuf::Buffered(_))) { |
| 183 |
break; |
| 184 |
} |
| 185 |
} |
| 186 |
Err(e) => return Err((counted, format!("{e}"))), |
| 187 |
} |
| 188 |
} |
| 189 |
Ok((counted, content)) |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
pub fn inspect_archive( |
| 203 |
data: &[u8], |
| 204 |
file_type: FileType, |
| 205 |
yara_rules: Option<&yara_x::Rules>, |
| 206 |
) -> (LayerResult, LayerResult) { |
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
if file_type != FileType::Download |
| 214 |
&& let Some(container) = detect_unsupported_container(data) |
| 215 |
{ |
| 216 |
let detail = format!( |
| 217 |
"{container} archives are not accepted for this upload type (cannot be decompression-bomb inspected)" |
| 218 |
); |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
return (error(detail.clone()), nested(LayerVerdict::Error, detail)); |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
let bomb = file_type != FileType::Cover; |
| 229 |
|
| 230 |
match detect_kind(data) { |
| 231 |
Some(ArchiveKind::Zip) => walk_zip(Cursor::new(data), bomb, true, yara_rules), |
| 232 |
Some(stream) => walk_compressed( |
| 233 |
stream, |
| 234 |
data.len() as u64, |
| 235 |
Cursor::new(data), |
| 236 |
bomb, |
| 237 |
true, |
| 238 |
yara_rules, |
| 239 |
), |
| 240 |
None if has_zip_eocd(data) => { |
| 241 |
|
| 242 |
|
| 243 |
walk_zip(Cursor::new(data), bomb, true, yara_rules) |
| 244 |
} |
| 245 |
None => ( |
| 246 |
if bomb { |
| 247 |
skip("Not a recognized archive") |
| 248 |
} else { |
| 249 |
skip("Archive check skipped for cover images") |
| 250 |
}, |
| 251 |
nested( |
| 252 |
LayerVerdict::Skip, |
| 253 |
"Not an archive; no interior to scan".to_string(), |
| 254 |
), |
| 255 |
), |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
|
| 260 |
fn bomb_disabled_archive() -> LayerResult { |
| 261 |
skip("Archive check skipped for cover images") |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
fn walk_zip<R: std::io::Read + std::io::Seek>( |
| 267 |
reader: R, |
| 268 |
bomb: bool, |
| 269 |
content: bool, |
| 270 |
yara_rules: Option<&yara_x::Rules>, |
| 271 |
) -> (LayerResult, LayerResult) { |
| 272 |
let mut archive = match zip::ZipArchive::new(reader) { |
| 273 |
Ok(a) => a, |
| 274 |
Err(e) => { |
| 275 |
return ( |
| 276 |
if bomb { |
| 277 |
LayerResult { |
| 278 |
layer: "archive", |
| 279 |
verdict: LayerVerdict::Error, |
| 280 |
detail: Some(format!("Failed to parse ZIP: {e}")), |
| 281 |
} |
| 282 |
} else { |
| 283 |
bomb_disabled_archive() |
| 284 |
}, |
| 285 |
if content { |
| 286 |
nested(LayerVerdict::Error, format!("cannot open nested ZIP: {e}")) |
| 287 |
} else { |
| 288 |
nested(LayerVerdict::Skip, String::new()) |
| 289 |
}, |
| 290 |
); |
| 291 |
} |
| 292 |
}; |
| 293 |
|
| 294 |
let count = archive.len(); |
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
let mut archive_res: Option<LayerResult> = None; |
| 301 |
let mut nested_res: Option<LayerResult> = None; |
| 302 |
|
| 303 |
if count > constants::SCAN_ZIP_MAX_ENTRIES { |
| 304 |
if bomb { |
| 305 |
archive_res = Some(LayerResult { |
| 306 |
layer: "archive", |
| 307 |
verdict: LayerVerdict::Fail, |
| 308 |
detail: Some(format!( |
| 309 |
"ZIP entry count {count} exceeds limit {}", |
| 310 |
constants::SCAN_ZIP_MAX_ENTRIES |
| 311 |
)), |
| 312 |
}); |
| 313 |
} |
| 314 |
if content { |
| 315 |
nested_res = Some(nested( |
| 316 |
LayerVerdict::Error, |
| 317 |
format!( |
| 318 |
"nested ZIP entry count {count} exceeds limit {}", |
| 319 |
constants::SCAN_ZIP_MAX_ENTRIES |
| 320 |
), |
| 321 |
)); |
| 322 |
} |
| 323 |
return ( |
| 324 |
archive_res.unwrap_or_else(bomb_disabled_archive), |
| 325 |
nested_res.unwrap_or_else(|| nested(LayerVerdict::Skip, String::new())), |
| 326 |
); |
| 327 |
} |
| 328 |
|
| 329 |
let mut total_compressed: u64 = 0; |
| 330 |
let mut total_uncompressed: u64 = 0; |
| 331 |
let mut interior_budget: u64 = constants::SCAN_ZIP_MAX_UNCOMPRESSED; |
| 332 |
|
| 333 |
for i in 0..count { |
| 334 |
|
| 335 |
let bomb_active = bomb && archive_res.is_none(); |
| 336 |
let content_active = content && nested_res.is_none(); |
| 337 |
if !bomb_active && !content_active { |
| 338 |
break; |
| 339 |
} |
| 340 |
|
| 341 |
let (name, entry_compressed, claimed_size) = match archive.by_index_raw(i) { |
| 342 |
Ok(e) => (e.name().to_string(), e.compressed_size(), e.size()), |
| 343 |
Err(e) => { |
| 344 |
if bomb_active { |
| 345 |
archive_res = Some(LayerResult { |
| 346 |
layer: "archive", |
| 347 |
verdict: LayerVerdict::Error, |
| 348 |
detail: Some(format!("Failed to read ZIP entry {i}: {e}")), |
| 349 |
}); |
| 350 |
} |
| 351 |
if content_active { |
| 352 |
nested_res = Some(nested( |
| 353 |
LayerVerdict::Error, |
| 354 |
format!("read nested ZIP entry {i}: {e}"), |
| 355 |
)); |
| 356 |
} |
| 357 |
continue; |
| 358 |
} |
| 359 |
}; |
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
if bomb_active { |
| 364 |
let name_lower = name.to_ascii_lowercase(); |
| 365 |
if name.contains("../") |
| 366 |
|| name.contains("..\\") |
| 367 |
|| name_lower.contains("%2e%2e") |
| 368 |
|| name.starts_with('/') |
| 369 |
|| name.contains('\0') |
| 370 |
{ |
| 371 |
archive_res = Some(LayerResult { |
| 372 |
layer: "archive", |
| 373 |
verdict: LayerVerdict::Fail, |
| 374 |
detail: Some(format!("Path traversal in entry: {name}")), |
| 375 |
}); |
| 376 |
|
| 377 |
if !content_active { |
| 378 |
break; |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
let entry_stop_limit = entry_bomb_stop_limit(entry_compressed); |
| 389 |
let want_content = content && nested_res.is_none(); |
| 390 |
let (counted, content_buf, decode_err) = match archive.by_index(i) { |
| 391 |
Ok(mut entry) => match tee_decompress( |
| 392 |
&mut entry, |
| 393 |
entry_stop_limit, |
| 394 |
want_content, |
| 395 |
&mut interior_budget, |
| 396 |
) { |
| 397 |
Ok((c, cb)) => (c, cb, None), |
| 398 |
Err((c, why)) => (c, None, Some(why)), |
| 399 |
}, |
| 400 |
|
| 401 |
|
| 402 |
Err(e) => ( |
| 403 |
claimed_size.saturating_mul(10).max(1024 * 1024), |
| 404 |
None, |
| 405 |
Some(format!("{e}")), |
| 406 |
), |
| 407 |
}; |
| 408 |
|
| 409 |
|
| 410 |
if bomb && archive_res.is_none() { |
| 411 |
|
| 412 |
|
| 413 |
let actual_size = if decode_err.is_some() { |
| 414 |
claimed_size.saturating_mul(10).max(1024 * 1024) |
| 415 |
} else { |
| 416 |
counted |
| 417 |
}; |
| 418 |
if actual_size > constants::SCAN_ZIP_MAX_UNCOMPRESSED { |
| 419 |
archive_res = Some(LayerResult { |
| 420 |
layer: "archive", |
| 421 |
verdict: LayerVerdict::Fail, |
| 422 |
detail: Some(format!( |
| 423 |
"Actual decompressed size exceeds {} bytes (possible ZIP bomb)", |
| 424 |
constants::SCAN_ZIP_MAX_UNCOMPRESSED |
| 425 |
)), |
| 426 |
}); |
| 427 |
} else { |
| 428 |
total_compressed += entry_compressed; |
| 429 |
total_uncompressed += actual_size; |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
|
| 435 |
|
| 436 |
|
| 437 |
if total_uncompressed > constants::SCAN_ZIP_MAX_UNCOMPRESSED { |
| 438 |
break; |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
if entry_compressed > 0 && actual_size >= 64 * 1024 { |
| 448 |
let entry_ratio = actual_size as f64 / entry_compressed as f64; |
| 449 |
if entry_ratio > constants::SCAN_ZIP_MAX_RATIO { |
| 450 |
archive_res = Some(LayerResult { |
| 451 |
layer: "archive", |
| 452 |
verdict: LayerVerdict::Fail, |
| 453 |
detail: Some(format!( |
| 454 |
"Entry {name} compression ratio {entry_ratio:.1}x exceeds limit of {:.0}x (possible ZIP bomb)", |
| 455 |
constants::SCAN_ZIP_MAX_RATIO |
| 456 |
)), |
| 457 |
}); |
| 458 |
} |
| 459 |
} |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
if content && nested_res.is_none() { |
| 465 |
if let Some(why) = decode_err { |
| 466 |
nested_res = Some(nested( |
| 467 |
LayerVerdict::Error, |
| 468 |
format!("decode nested entry: {why}"), |
| 469 |
)); |
| 470 |
} else { |
| 471 |
match content_buf { |
| 472 |
Some(ContentBuf::Buffered(bytes)) => { |
| 473 |
if let Some(v) = scan_entry( |
| 474 |
&bytes, |
| 475 |
yara_rules, |
| 476 |
constants::SCAN_ZIP_MAX_DEPTH, |
| 477 |
&mut interior_budget, |
| 478 |
) { |
| 479 |
nested_res = Some(v); |
| 480 |
} |
| 481 |
} |
| 482 |
Some(ContentBuf::Overflow) => { |
| 483 |
nested_res = Some(nested( |
| 484 |
LayerVerdict::Error, |
| 485 |
format!( |
| 486 |
"nested entry exceeds {INTERIOR_ENTRY_MAX}-byte interior scan ceiling" |
| 487 |
), |
| 488 |
)); |
| 489 |
} |
| 490 |
Some(ContentBuf::BudgetExceeded) => { |
| 491 |
nested_res = Some(nested( |
| 492 |
LayerVerdict::Error, |
| 493 |
"nested archive content exceeds total interior scan budget".to_string(), |
| 494 |
)); |
| 495 |
} |
| 496 |
None => {} |
| 497 |
} |
| 498 |
} |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
let archive_result = match archive_res { |
| 504 |
Some(r) => r, |
| 505 |
None if !bomb => bomb_disabled_archive(), |
| 506 |
None => { |
| 507 |
if total_uncompressed > constants::SCAN_ZIP_MAX_UNCOMPRESSED { |
| 508 |
LayerResult { |
| 509 |
layer: "archive", |
| 510 |
verdict: LayerVerdict::Fail, |
| 511 |
detail: Some(format!( |
| 512 |
"Total uncompressed size {total_uncompressed} bytes exceeds limit of {} bytes", |
| 513 |
constants::SCAN_ZIP_MAX_UNCOMPRESSED |
| 514 |
)), |
| 515 |
} |
| 516 |
} else if total_compressed > 0 |
| 517 |
&& (total_uncompressed as f64 / total_compressed as f64) |
| 518 |
> constants::SCAN_ZIP_MAX_RATIO |
| 519 |
{ |
| 520 |
LayerResult { |
| 521 |
layer: "archive", |
| 522 |
verdict: LayerVerdict::Fail, |
| 523 |
detail: Some(format!( |
| 524 |
"Compression ratio {:.1}x exceeds limit of {:.0}x (possible ZIP bomb)", |
| 525 |
total_uncompressed as f64 / total_compressed as f64, |
| 526 |
constants::SCAN_ZIP_MAX_RATIO |
| 527 |
)), |
| 528 |
} |
| 529 |
} else { |
| 530 |
LayerResult { |
| 531 |
layer: "archive", |
| 532 |
verdict: LayerVerdict::Pass, |
| 533 |
detail: Some(format!( |
| 534 |
"{count} entries, {:.1}x ratio", |
| 535 |
if total_compressed > 0 { |
| 536 |
total_uncompressed as f64 / total_compressed as f64 |
| 537 |
} else { |
| 538 |
0.0 |
| 539 |
} |
| 540 |
)), |
| 541 |
} |
| 542 |
} |
| 543 |
} |
| 544 |
}; |
| 545 |
|
| 546 |
let nested_result = match nested_res { |
| 547 |
Some(r) => r, |
| 548 |
None if !content => nested(LayerVerdict::Skip, String::new()), |
| 549 |
None => nested( |
| 550 |
LayerVerdict::Pass, |
| 551 |
"Archive interior fully scanned; no threats found".to_string(), |
| 552 |
), |
| 553 |
}; |
| 554 |
|
| 555 |
(archive_result, nested_result) |
| 556 |
} |
| 557 |
|
| 558 |
|
| 559 |
|
| 560 |
|
| 561 |
fn walk_compressed<R: Read>( |
| 562 |
kind: ArchiveKind, |
| 563 |
compressed_size: u64, |
| 564 |
reader: R, |
| 565 |
bomb: bool, |
| 566 |
content: bool, |
| 567 |
yara_rules: Option<&yara_x::Rules>, |
| 568 |
) -> (LayerResult, LayerResult) { |
| 569 |
let mut decoder: Box<dyn Read> = match kind { |
| 570 |
ArchiveKind::Gzip => Box::new(flate2::read::MultiGzDecoder::new(reader)), |
| 571 |
ArchiveKind::Bzip2 => Box::new(bzip2::read::BzDecoder::new(reader)), |
| 572 |
ArchiveKind::Xz => Box::new(xz2::read::XzDecoder::new(reader)), |
| 573 |
ArchiveKind::Zstd => match zstd::stream::read::Decoder::new(reader) { |
| 574 |
Ok(d) => Box::new(d), |
| 575 |
Err(e) => { |
| 576 |
let why = format!("zstd init failed: {e}"); |
| 577 |
return ( |
| 578 |
if bomb { |
| 579 |
error(why.clone()) |
| 580 |
} else { |
| 581 |
bomb_disabled_archive() |
| 582 |
}, |
| 583 |
if content { |
| 584 |
nested(LayerVerdict::Error, why) |
| 585 |
} else { |
| 586 |
nested(LayerVerdict::Skip, String::new()) |
| 587 |
}, |
| 588 |
); |
| 589 |
} |
| 590 |
}, |
| 591 |
ArchiveKind::Zip => unreachable!("zip is handled by walk_zip"), |
| 592 |
}; |
| 593 |
|
| 594 |
let abs_limit = constants::SCAN_ZIP_MAX_UNCOMPRESSED; |
| 595 |
let ratio_limit = compressed_size.saturating_mul(constants::SCAN_ZIP_MAX_RATIO as u64); |
| 596 |
let mut interior_budget: u64 = constants::SCAN_ZIP_MAX_UNCOMPRESSED; |
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
let stop_limit = entry_bomb_stop_limit(compressed_size); |
| 602 |
let (counted, content_buf, decode_err) = |
| 603 |
match tee_decompress(decoder.as_mut(), stop_limit, content, &mut interior_budget) { |
| 604 |
Ok((c, cb)) => (c, cb, None), |
| 605 |
Err((c, why)) => (c, None, Some(why)), |
| 606 |
}; |
| 607 |
|
| 608 |
|
| 609 |
let archive_result = if !bomb { |
| 610 |
bomb_disabled_archive() |
| 611 |
} else if let Some(ref why) = decode_err { |
| 612 |
|
| 613 |
error(format!("{} decode error: {why}", kind.label())) |
| 614 |
} else if counted > abs_limit { |
| 615 |
LayerResult { |
| 616 |
layer: "archive", |
| 617 |
verdict: LayerVerdict::Fail, |
| 618 |
detail: Some(format!( |
| 619 |
"{} stream decompresses past {abs_limit} bytes (possible decompression bomb)", |
| 620 |
kind.label() |
| 621 |
)), |
| 622 |
} |
| 623 |
} else if compressed_size > 0 && counted > ratio_limit { |
| 624 |
LayerResult { |
| 625 |
layer: "archive", |
| 626 |
verdict: LayerVerdict::Fail, |
| 627 |
detail: Some(format!( |
| 628 |
"{} compression ratio exceeds {:.0}x (possible decompression bomb)", |
| 629 |
kind.label(), |
| 630 |
constants::SCAN_ZIP_MAX_RATIO |
| 631 |
)), |
| 632 |
} |
| 633 |
} else { |
| 634 |
LayerResult { |
| 635 |
layer: "archive", |
| 636 |
verdict: LayerVerdict::Pass, |
| 637 |
detail: Some(format!( |
| 638 |
"{} stream, {counted} bytes uncompressed ({:.1}x)", |
| 639 |
kind.label(), |
| 640 |
if compressed_size > 0 { |
| 641 |
counted as f64 / compressed_size as f64 |
| 642 |
} else { |
| 643 |
0.0 |
| 644 |
} |
| 645 |
)), |
| 646 |
} |
| 647 |
}; |
| 648 |
|
| 649 |
|
| 650 |
let nested_result = if !content { |
| 651 |
nested(LayerVerdict::Skip, String::new()) |
| 652 |
} else if let Some(why) = decode_err { |
| 653 |
nested(LayerVerdict::Error, format!("decode nested entry: {why}")) |
| 654 |
} else { |
| 655 |
match content_buf { |
| 656 |
Some(ContentBuf::Buffered(bytes)) => scan_entry( |
| 657 |
&bytes, |
| 658 |
yara_rules, |
| 659 |
constants::SCAN_ZIP_MAX_DEPTH, |
| 660 |
&mut interior_budget, |
| 661 |
) |
| 662 |
.unwrap_or_else(|| { |
| 663 |
nested( |
| 664 |
LayerVerdict::Pass, |
| 665 |
"Archive interior fully scanned; no threats found".to_string(), |
| 666 |
) |
| 667 |
}), |
| 668 |
Some(ContentBuf::Overflow) => nested( |
| 669 |
LayerVerdict::Error, |
| 670 |
format!("nested entry exceeds {INTERIOR_ENTRY_MAX}-byte interior scan ceiling"), |
| 671 |
), |
| 672 |
Some(ContentBuf::BudgetExceeded) => nested( |
| 673 |
LayerVerdict::Error, |
| 674 |
"nested archive content exceeds total interior scan budget".to_string(), |
| 675 |
), |
| 676 |
None => nested( |
| 677 |
LayerVerdict::Pass, |
| 678 |
"Archive interior fully scanned; no threats found".to_string(), |
| 679 |
), |
| 680 |
} |
| 681 |
}; |
| 682 |
|
| 683 |
(archive_result, nested_result) |
| 684 |
} |
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
#[cfg(test)] |
| 694 |
pub fn check_archive_safety_path(path: &std::path::Path, file_type: FileType) -> LayerResult { |
| 695 |
use std::io::{Seek, SeekFrom}; |
| 696 |
|
| 697 |
if file_type == FileType::Cover { |
| 698 |
return skip("Archive check skipped for cover images"); |
| 699 |
} |
| 700 |
|
| 701 |
let mut file = match std::fs::File::open(path) { |
| 702 |
Ok(f) => f, |
| 703 |
Err(e) => return error(format!("open spool {}: {e}", path.display())), |
| 704 |
}; |
| 705 |
|
| 706 |
let mut magic = [0u8; 6]; |
| 707 |
let read = file.read(&mut magic).unwrap_or(0); |
| 708 |
let kind = detect_kind(&magic[..read]); |
| 709 |
|
| 710 |
if file.seek(SeekFrom::Start(0)).is_err() { |
| 711 |
return error(format!("seek spool {}", path.display())); |
| 712 |
} |
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
match kind { |
| 718 |
Some(ArchiveKind::Zip) => walk_zip(file, true, false, None).0, |
| 719 |
Some(stream) => { |
| 720 |
let compressed_size = std::fs::metadata(path).map_or(0, |m| m.len()); |
| 721 |
walk_compressed(stream, compressed_size, file, true, false, None).0 |
| 722 |
} |
| 723 |
None => { |
| 724 |
|
| 725 |
|
| 726 |
let len = std::fs::metadata(path).map_or(0, |m| m.len()); |
| 727 |
let window = 22 + u16::MAX as u64; |
| 728 |
let start = len.saturating_sub(window); |
| 729 |
let mut tail = Vec::new(); |
| 730 |
let is_zip = file.seek(SeekFrom::Start(start)).is_ok() |
| 731 |
&& file.read_to_end(&mut tail).is_ok() |
| 732 |
&& has_zip_eocd(&tail); |
| 733 |
if is_zip { |
| 734 |
if file.seek(SeekFrom::Start(0)).is_err() { |
| 735 |
return error(format!("seek spool {}", path.display())); |
| 736 |
} |
| 737 |
walk_zip(file, true, false, None).0 |
| 738 |
} else { |
| 739 |
skip("Not a recognized archive") |
| 740 |
} |
| 741 |
} |
| 742 |
} |
| 743 |
} |
| 744 |
|
| 745 |
fn skip(detail: &str) -> LayerResult { |
| 746 |
LayerResult { |
| 747 |
layer: "archive", |
| 748 |
verdict: LayerVerdict::Skip, |
| 749 |
detail: Some(detail.to_string()), |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
fn error(detail: String) -> LayerResult { |
| 754 |
LayerResult { |
| 755 |
layer: "archive", |
| 756 |
verdict: LayerVerdict::Error, |
| 757 |
detail: Some(detail), |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
pub fn is_archive(data: &[u8]) -> bool { |
| 764 |
detect_kind(data).is_some() || has_zip_eocd(data) |
| 765 |
} |
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
const INTERIOR_ENTRY_MAX: usize = constants::SCAN_MAX_MEMORY_BYTES; |
| 772 |
|
| 773 |
fn nested(verdict: LayerVerdict, detail: String) -> LayerResult { |
| 774 |
LayerResult { |
| 775 |
layer: "archive_nested", |
| 776 |
verdict, |
| 777 |
detail: Some(detail), |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
pub fn scan_nested_contents(data: &[u8], yara_rules: Option<&yara_x::Rules>) -> LayerResult { |
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
inspect_archive(data, FileType::Download, yara_rules).1 |
| 802 |
} |
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
fn scan_interior( |
| 807 |
data: &[u8], |
| 808 |
yara_rules: Option<&yara_x::Rules>, |
| 809 |
depth: u32, |
| 810 |
budget: &mut u64, |
| 811 |
) -> Option<LayerResult> { |
| 812 |
match detect_kind(data) { |
| 813 |
Some(ArchiveKind::Zip) => scan_zip_interior(Cursor::new(data), yara_rules, depth, budget), |
| 814 |
Some(stream) => match decompress_one_bounded(stream, Cursor::new(data), budget) { |
| 815 |
Ok(bytes) => scan_entry(&bytes, yara_rules, depth, budget), |
| 816 |
Err(why) => Some(nested(LayerVerdict::Error, why)), |
| 817 |
}, |
| 818 |
None if has_zip_eocd(data) => { |
| 819 |
scan_zip_interior(Cursor::new(data), yara_rules, depth, budget) |
| 820 |
} |
| 821 |
None => None, |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
fn scan_zip_interior<R: Read + std::io::Seek>( |
| 826 |
reader: R, |
| 827 |
yara_rules: Option<&yara_x::Rules>, |
| 828 |
depth: u32, |
| 829 |
budget: &mut u64, |
| 830 |
) -> Option<LayerResult> { |
| 831 |
let mut archive = match zip::ZipArchive::new(reader) { |
| 832 |
Ok(a) => a, |
| 833 |
Err(e) => { |
| 834 |
return Some(nested( |
| 835 |
LayerVerdict::Error, |
| 836 |
format!("cannot open nested ZIP: {e}"), |
| 837 |
)); |
| 838 |
} |
| 839 |
}; |
| 840 |
if archive.len() > constants::SCAN_ZIP_MAX_ENTRIES { |
| 841 |
return Some(nested( |
| 842 |
LayerVerdict::Error, |
| 843 |
format!( |
| 844 |
"nested ZIP entry count {} exceeds limit {}", |
| 845 |
archive.len(), |
| 846 |
constants::SCAN_ZIP_MAX_ENTRIES |
| 847 |
), |
| 848 |
)); |
| 849 |
} |
| 850 |
for i in 0..archive.len() { |
| 851 |
let bytes = match read_zip_entry_bounded(&mut archive, i, budget) { |
| 852 |
Ok(b) => b, |
| 853 |
Err(why) => return Some(nested(LayerVerdict::Error, why)), |
| 854 |
}; |
| 855 |
if let Some(v) = scan_entry(&bytes, yara_rules, depth, budget) { |
| 856 |
return Some(v); |
| 857 |
} |
| 858 |
} |
| 859 |
None |
| 860 |
} |
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
fn scan_entry( |
| 865 |
bytes: &[u8], |
| 866 |
yara_rules: Option<&yara_x::Rules>, |
| 867 |
depth: u32, |
| 868 |
budget: &mut u64, |
| 869 |
) -> Option<LayerResult> { |
| 870 |
let yara_result = match yara_rules { |
| 871 |
Some(rules) => super::yara::scan_with_yara(rules, bytes), |
| 872 |
None => LayerResult { |
| 873 |
layer: "yara", |
| 874 |
verdict: LayerVerdict::Skip, |
| 875 |
detail: None, |
| 876 |
}, |
| 877 |
}; |
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
let checks = [ |
| 882 |
super::content_type::verify_content_type(bytes, FileType::Download), |
| 883 |
super::structural::analyze_binary(bytes, FileType::Download), |
| 884 |
yara_result, |
| 885 |
]; |
| 886 |
for r in checks { |
| 887 |
match r.verdict { |
| 888 |
LayerVerdict::Fail => { |
| 889 |
return Some(nested( |
| 890 |
LayerVerdict::Fail, |
| 891 |
format!( |
| 892 |
"nested archive entry flagged by {}: {}", |
| 893 |
r.layer, |
| 894 |
r.detail.unwrap_or_default() |
| 895 |
), |
| 896 |
)); |
| 897 |
} |
| 898 |
LayerVerdict::Error if super::error_policy_for(r.layer) == ErrorPolicy::FailClosed => { |
| 899 |
return Some(nested( |
| 900 |
LayerVerdict::Error, |
| 901 |
format!( |
| 902 |
"nested archive entry: {} layer errored: {}", |
| 903 |
r.layer, |
| 904 |
r.detail.unwrap_or_default() |
| 905 |
), |
| 906 |
)); |
| 907 |
} |
| 908 |
_ => {} |
| 909 |
} |
| 910 |
} |
| 911 |
if is_archive(bytes) { |
| 912 |
if depth == 0 { |
| 913 |
return Some(nested( |
| 914 |
LayerVerdict::Error, |
| 915 |
"nested archive exceeds maximum scan depth; held for review".to_string(), |
| 916 |
)); |
| 917 |
} |
| 918 |
return scan_interior(bytes, yara_rules, depth - 1, budget); |
| 919 |
} |
| 920 |
None |
| 921 |
} |
| 922 |
|
| 923 |
fn read_zip_entry_bounded<R: Read + std::io::Seek>( |
| 924 |
archive: &mut zip::ZipArchive<R>, |
| 925 |
index: usize, |
| 926 |
budget: &mut u64, |
| 927 |
) -> Result<Vec<u8>, String> { |
| 928 |
let mut entry = archive |
| 929 |
.by_index(index) |
| 930 |
.map_err(|e| format!("read nested ZIP entry {index}: {e}"))?; |
| 931 |
read_bounded(&mut entry, budget) |
| 932 |
} |
| 933 |
|
| 934 |
fn decompress_one_bounded<R: Read>( |
| 935 |
kind: ArchiveKind, |
| 936 |
reader: R, |
| 937 |
budget: &mut u64, |
| 938 |
) -> Result<Vec<u8>, String> { |
| 939 |
let mut decoder: Box<dyn Read> = match kind { |
| 940 |
ArchiveKind::Gzip => Box::new(flate2::read::MultiGzDecoder::new(reader)), |
| 941 |
ArchiveKind::Bzip2 => Box::new(bzip2::read::BzDecoder::new(reader)), |
| 942 |
ArchiveKind::Xz => Box::new(xz2::read::XzDecoder::new(reader)), |
| 943 |
ArchiveKind::Zstd => zstd::stream::read::Decoder::new(reader) |
| 944 |
.map(|d| Box::new(d) as Box<dyn Read>) |
| 945 |
.map_err(|e| format!("zstd init failed: {e}"))?, |
| 946 |
ArchiveKind::Zip => return Err("zip handled separately".to_string()), |
| 947 |
}; |
| 948 |
read_bounded(decoder.as_mut(), budget) |
| 949 |
} |
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
fn read_bounded(reader: &mut dyn Read, budget: &mut u64) -> Result<Vec<u8>, String> { |
| 955 |
let mut out: Vec<u8> = Vec::new(); |
| 956 |
let mut buf = [0u8; 8192]; |
| 957 |
loop { |
| 958 |
match reader.read(&mut buf) { |
| 959 |
Ok(0) => break, |
| 960 |
Ok(n) => { |
| 961 |
if out.len() + n > INTERIOR_ENTRY_MAX { |
| 962 |
return Err(format!( |
| 963 |
"nested entry exceeds {INTERIOR_ENTRY_MAX}-byte interior scan ceiling" |
| 964 |
)); |
| 965 |
} |
| 966 |
if n as u64 > *budget { |
| 967 |
return Err( |
| 968 |
"nested archive content exceeds total interior scan budget".to_string() |
| 969 |
); |
| 970 |
} |
| 971 |
*budget -= n as u64; |
| 972 |
out.extend_from_slice(&buf[..n]); |
| 973 |
} |
| 974 |
Err(e) => return Err(format!("decode nested entry: {e}")), |
| 975 |
} |
| 976 |
} |
| 977 |
Ok(out) |
| 978 |
} |
| 979 |
|
| 980 |
#[cfg(test)] |
| 981 |
mod tests { |
| 982 |
use super::*; |
| 983 |
use zip::write::SimpleFileOptions; |
| 984 |
|
| 985 |
fn make_zip(entries: &[(&str, &[u8])]) -> Vec<u8> { |
| 986 |
let buf = Vec::new(); |
| 987 |
let cursor = Cursor::new(buf); |
| 988 |
let mut writer = zip::ZipWriter::new(cursor); |
| 989 |
let options = |
| 990 |
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); |
| 991 |
for (name, data) in entries { |
| 992 |
writer.start_file(*name, options).unwrap(); |
| 993 |
std::io::Write::write_all(&mut writer, data).unwrap(); |
| 994 |
} |
| 995 |
writer.finish().unwrap().into_inner() |
| 996 |
} |
| 997 |
|
| 998 |
fn make_compressed_zip(entries: &[(&str, &[u8])]) -> Vec<u8> { |
| 999 |
let buf = Vec::new(); |
| 1000 |
let cursor = Cursor::new(buf); |
| 1001 |
let mut writer = zip::ZipWriter::new(cursor); |
| 1002 |
let options = |
| 1003 |
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); |
| 1004 |
for (name, data) in entries { |
| 1005 |
writer.start_file(*name, options).unwrap(); |
| 1006 |
std::io::Write::write_all(&mut writer, data).unwrap(); |
| 1007 |
} |
| 1008 |
writer.finish().unwrap().into_inner() |
| 1009 |
} |
| 1010 |
|
| 1011 |
|
| 1012 |
|
| 1013 |
#[test] |
| 1014 |
fn non_zip_skipped() { |
| 1015 |
let result = check_archive_safety(b"not a zip file", FileType::Download); |
| 1016 |
assert_eq!(result.verdict, LayerVerdict::Skip); |
| 1017 |
} |
| 1018 |
|
| 1019 |
#[test] |
| 1020 |
fn audio_non_zip_skipped() { |
| 1021 |
let result = check_archive_safety(b"audio data", FileType::Audio); |
| 1022 |
assert_eq!(result.verdict, LayerVerdict::Skip); |
| 1023 |
} |
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
#[test] |
| 1028 |
fn sevenzip_rejected_for_non_download() { |
| 1029 |
let data = [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, 0, 0, 0, 0]; |
| 1030 |
let result = check_archive_safety(&data, FileType::Cover); |
| 1031 |
assert_eq!(result.verdict, LayerVerdict::Error); |
| 1032 |
} |
| 1033 |
|
| 1034 |
#[test] |
| 1035 |
fn sevenzip_allowed_for_download() { |
| 1036 |
|
| 1037 |
let data = [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C, 0, 0, 0, 0]; |
| 1038 |
let result = check_archive_safety(&data, FileType::Download); |
| 1039 |
assert_ne!(result.verdict, LayerVerdict::Error); |
| 1040 |
} |
| 1041 |
|
| 1042 |
#[test] |
| 1043 |
fn rar_rejected_for_non_download() { |
| 1044 |
let data = [0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00, 0, 0, 0]; |
| 1045 |
let result = check_archive_safety(&data, FileType::MediaImage); |
| 1046 |
assert_eq!(result.verdict, LayerVerdict::Error); |
| 1047 |
} |
| 1048 |
|
| 1049 |
#[test] |
| 1050 |
fn cover_zip_skipped() { |
| 1051 |
|
| 1052 |
let data = make_zip(&[("test.txt", b"hello")]); |
| 1053 |
let result = check_archive_safety(&data, FileType::Cover); |
| 1054 |
assert_eq!(result.verdict, LayerVerdict::Skip); |
| 1055 |
} |
| 1056 |
|
| 1057 |
|
| 1058 |
|
| 1059 |
#[test] |
| 1060 |
fn valid_zip_passes() { |
| 1061 |
let data = make_zip(&[("test.txt", b"hello world")]); |
| 1062 |
let result = check_archive_safety(&data, FileType::Download); |
| 1063 |
assert_eq!(result.verdict, LayerVerdict::Pass); |
| 1064 |
} |
| 1065 |
|
| 1066 |
#[test] |
| 1067 |
fn empty_zip_passes() { |
| 1068 |
let buf = Vec::new(); |
| 1069 |
let cursor = Cursor::new(buf); |
| 1070 |
let writer = zip::ZipWriter::new(cursor); |
| 1071 |
let data = writer.finish().unwrap().into_inner(); |
| 1072 |
|
| 1073 |
|
| 1074 |
|
| 1075 |
let result = check_archive_safety(&data, FileType::Download); |
| 1076 |
|
| 1077 |
assert!( |
| 1078 |
result.verdict == LayerVerdict::Skip || result.verdict == LayerVerdict::Pass, |
| 1079 |
"unexpected verdict: {:?}", |
| 1080 |
result.verdict |
| 1081 |
); |
| 1082 |
} |
| 1083 |
|
| 1084 |
#[test] |
| 1085 |
fn multi_entry_zip_passes() { |
| 1086 |
let data = make_zip(&[ |
| 1087 |
("file1.txt", b"content one"), |
| 1088 |
("subdir/file2.txt", b"content two"), |
| 1089 |
("readme.md", b"# hello"), |
| 1090 |
]); |
| 1091 |
let result = check_archive_safety(&data, FileType::Download); |
| 1092 |
assert_eq!(result.verdict, LayerVerdict::Pass); |
| 1093 |
assert!(result.detail.unwrap().contains("3 entries")); |
| 1094 |
} |
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
#[test] |
| 1099 |
fn zip_with_forward_slash_traversal_fails() { |
| 1100 |
let data = make_zip(&[("../../../etc/passwd", b"pwned")]); |
| 1101 |
let result = check_archive_safety(&data, FileType::Download); |
| 1102 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1103 |
assert!(result.detail.unwrap().contains("Path traversal")); |
| 1104 |
} |
| 1105 |
|
| 1106 |
#[test] |
| 1107 |
fn zip_with_backslash_traversal_fails() { |
| 1108 |
let data = make_zip(&[("..\\..\\Windows\\System32\\config", b"pwned")]); |
| 1109 |
let result = check_archive_safety(&data, FileType::Download); |
| 1110 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1111 |
assert!(result.detail.unwrap().contains("Path traversal")); |
| 1112 |
} |
| 1113 |
|
| 1114 |
#[test] |
| 1115 |
fn zip_with_mid_path_traversal_fails() { |
| 1116 |
let data = make_zip(&[("safe/../../etc/passwd", b"pwned")]); |
| 1117 |
let result = check_archive_safety(&data, FileType::Download); |
| 1118 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1119 |
} |
| 1120 |
|
| 1121 |
#[test] |
| 1122 |
fn zip_with_url_encoded_traversal_fails() { |
| 1123 |
|
| 1124 |
let data = make_zip(&[("%2E%2E/secrets", b"pwned")]); |
| 1125 |
let result = check_archive_safety(&data, FileType::Download); |
| 1126 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1127 |
assert!(result.detail.unwrap().contains("Path traversal")); |
| 1128 |
} |
| 1129 |
|
| 1130 |
#[test] |
| 1131 |
fn zip_with_absolute_path_fails() { |
| 1132 |
let data = make_zip(&[("/etc/passwd", b"pwned")]); |
| 1133 |
let result = check_archive_safety(&data, FileType::Download); |
| 1134 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1135 |
assert!(result.detail.unwrap().contains("Path traversal")); |
| 1136 |
} |
| 1137 |
|
| 1138 |
#[test] |
| 1139 |
fn zip_with_null_byte_in_name_fails() { |
| 1140 |
let data = make_zip(&[("legit.txt\0../escape", b"pwned")]); |
| 1141 |
let result = check_archive_safety(&data, FileType::Download); |
| 1142 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1143 |
assert!(result.detail.unwrap().contains("Path traversal")); |
| 1144 |
} |
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
fn test_yara_rules() -> yara_x::Rules { |
| 1159 |
super::super::yara::compile_rules_from_dir("yara-rules") |
| 1160 |
.expect("compile yara-rules") |
| 1161 |
.0 |
| 1162 |
.expect("yara-rules dir has rules") |
| 1163 |
} |
| 1164 |
|
| 1165 |
|
| 1166 |
const EICAR: &[u8] = br"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"; |
| 1167 |
|
| 1168 |
#[test] |
| 1169 |
fn benign_nested_zip_passes() { |
| 1170 |
let inner = make_zip(&[("hello.txt", b"hello world")]); |
| 1171 |
let outer = make_zip(&[("inner.zip", &inner), ("notes.txt", b"readme")]); |
| 1172 |
let result = scan_nested_contents(&outer, Some(&test_yara_rules())); |
| 1173 |
assert_eq!(result.verdict, LayerVerdict::Pass, "{:?}", result.detail); |
| 1174 |
} |
| 1175 |
|
| 1176 |
#[test] |
| 1177 |
fn eicar_in_zip_in_zip_is_caught() { |
| 1178 |
|
| 1179 |
|
| 1180 |
let inner = make_zip(&[("evil.txt", EICAR)]); |
| 1181 |
let outer = make_zip(&[("inner.zip", &inner)]); |
| 1182 |
let result = scan_nested_contents(&outer, Some(&test_yara_rules())); |
| 1183 |
assert_eq!( |
| 1184 |
result.verdict, |
| 1185 |
LayerVerdict::Fail, |
| 1186 |
"EICAR nested two zips deep must be caught, got {:?}", |
| 1187 |
result.detail |
| 1188 |
); |
| 1189 |
} |
| 1190 |
|
| 1191 |
#[test] |
| 1192 |
fn eicar_in_single_gzip_is_caught() { |
| 1193 |
|
| 1194 |
|
| 1195 |
let gz = gzip(EICAR); |
| 1196 |
let result = scan_nested_contents(&gz, Some(&test_yara_rules())); |
| 1197 |
assert_eq!(result.verdict, LayerVerdict::Fail, "{:?}", result.detail); |
| 1198 |
} |
| 1199 |
|
| 1200 |
#[test] |
| 1201 |
fn nesting_beyond_scan_depth_is_held_not_passed() { |
| 1202 |
|
| 1203 |
|
| 1204 |
|
| 1205 |
let mut nested = make_zip(&[("leaf.txt", b"benign")]); |
| 1206 |
for _ in 0..4 { |
| 1207 |
nested = make_zip(&[("inner.zip", &nested)]); |
| 1208 |
} |
| 1209 |
let result = scan_nested_contents(&nested, Some(&test_yara_rules())); |
| 1210 |
assert_eq!( |
| 1211 |
result.verdict, |
| 1212 |
LayerVerdict::Error, |
| 1213 |
"a nest deeper than the scan depth must be held, got {:?}", |
| 1214 |
result.detail |
| 1215 |
); |
| 1216 |
assert_eq!( |
| 1217 |
super::super::error_policy_for(result.layer), |
| 1218 |
ErrorPolicy::FailClosed |
| 1219 |
); |
| 1220 |
} |
| 1221 |
|
| 1222 |
#[test] |
| 1223 |
fn non_archive_has_no_interior() { |
| 1224 |
let result = scan_nested_contents(b"just some plain bytes", Some(&test_yara_rules())); |
| 1225 |
assert_eq!(result.verdict, LayerVerdict::Skip); |
| 1226 |
} |
| 1227 |
|
| 1228 |
#[test] |
| 1229 |
fn non_archive_extensions_ignored() { |
| 1230 |
let data = make_zip(&[ |
| 1231 |
("app.exe", b"binary"), |
| 1232 |
("readme.txt", b"hello"), |
| 1233 |
("image.png", b"pixels"), |
| 1234 |
]); |
| 1235 |
let result = check_archive_safety(&data, FileType::Download); |
| 1236 |
assert_eq!(result.verdict, LayerVerdict::Pass); |
| 1237 |
} |
| 1238 |
|
| 1239 |
|
| 1240 |
|
| 1241 |
#[test] |
| 1242 |
fn high_compression_ratio_fails() { |
| 1243 |
|
| 1244 |
|
| 1245 |
let zeros = vec![0u8; 1024 * 1024]; |
| 1246 |
let data = make_compressed_zip(&[("bomb.bin", &zeros)]); |
| 1247 |
let result = check_archive_safety(&data, FileType::Download); |
| 1248 |
assert_eq!( |
| 1249 |
result.verdict, |
| 1250 |
LayerVerdict::Fail, |
| 1251 |
"Expected Fail for high compression ratio, got: {:?}", |
| 1252 |
result.detail |
| 1253 |
); |
| 1254 |
assert!(result.detail.unwrap().contains("ZIP bomb")); |
| 1255 |
} |
| 1256 |
|
| 1257 |
#[test] |
| 1258 |
fn normal_compression_ratio_passes() { |
| 1259 |
|
| 1260 |
let data_bytes: Vec<u8> = (0..10000).map(|i| (i * 37 + 13) as u8).collect(); |
| 1261 |
let data = make_compressed_zip(&[("normal.bin", &data_bytes)]); |
| 1262 |
let result = check_archive_safety(&data, FileType::Download); |
| 1263 |
assert_eq!(result.verdict, LayerVerdict::Pass); |
| 1264 |
} |
| 1265 |
|
| 1266 |
|
| 1267 |
|
| 1268 |
#[test] |
| 1269 |
fn zip_disguised_as_audio_checked() { |
| 1270 |
|
| 1271 |
let data = make_zip(&[("test.txt", b"hello")]); |
| 1272 |
let result = check_archive_safety(&data, FileType::Audio); |
| 1273 |
assert_eq!(result.verdict, LayerVerdict::Pass); |
| 1274 |
} |
| 1275 |
|
| 1276 |
#[test] |
| 1277 |
fn zip_disguised_as_audio_with_traversal_fails() { |
| 1278 |
let data = make_zip(&[("../../../etc/passwd", b"pwned")]); |
| 1279 |
let result = check_archive_safety(&data, FileType::Audio); |
| 1280 |
assert_eq!(result.verdict, LayerVerdict::Fail); |
| 1281 |
} |
| 1282 |
|
| 1283 |
|
| 1284 |
|
| 1285 |
#[test] |
| 1286 |
fn corrupted_zip_magic_returns_error() { |
| 1287 |
|
| 1288 |
let mut data = vec![0x50, 0x4B, 0x03, 0x04]; |
| 1289 |
data.extend_from_slice(&[0xFF; 100]); |
| 1290 |
let result = check_archive_safety(&data, FileType::Download); |
| 1291 |
assert_eq!(result.verdict, LayerVerdict::Error); |
| 1292 |
assert!(result.detail.unwrap().contains("Failed to parse ZIP")); |
| 1293 |
} |
| 1294 |
|
| 1295 |
#[test] |
| 1296 |
fn path_entry_matches_buffered_for_non_zip() { |
| 1297 |
let data = b"not a zip at all"; |
| 1298 |
let buffered = check_archive_safety(data, FileType::Download); |
| 1299 |
let tmp = tempfile::NamedTempFile::new().unwrap(); |
| 1300 |
std::fs::write(tmp.path(), data).unwrap(); |
| 1301 |
let path_based = check_archive_safety_path(tmp.path(), FileType::Download); |
| 1302 |
assert_eq!(buffered.verdict, path_based.verdict); |
| 1303 |
assert_eq!(buffered.verdict, LayerVerdict::Skip); |
| 1304 |
} |
| 1305 |
|
| 1306 |
#[test] |
| 1307 |
fn path_entry_matches_buffered_for_cover_skip() { |
| 1308 |
let mut data = vec![0x50, 0x4B, 0x03, 0x04]; |
| 1309 |
data.extend_from_slice(&[0xFF; 100]); |
| 1310 |
let buffered = check_archive_safety(&data, FileType::Cover); |
| 1311 |
let tmp = tempfile::NamedTempFile::new().unwrap(); |
| 1312 |
std::fs::write(tmp.path(), &data).unwrap(); |
| 1313 |
let path_based = check_archive_safety_path(tmp.path(), FileType::Cover); |
| 1314 |
assert_eq!(buffered.verdict, path_based.verdict); |
| 1315 |
assert_eq!(buffered.verdict, LayerVerdict::Skip); |
| 1316 |
} |
| 1317 |
|
| 1318 |
|
| 1319 |
|
| 1320 |
use std::io::Write; |
| 1321 |
|
| 1322 |
fn gzip(data: &[u8]) -> Vec<u8> { |
| 1323 |
let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); |
| 1324 |
e.write_all(data).unwrap(); |
| 1325 |
e.finish().unwrap() |
| 1326 |
} |
| 1327 |
fn bzip2_compress(data: &[u8]) -> Vec<u8> { |
| 1328 |
let mut e = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::new(9)); |
| 1329 |
e.write_all(data).unwrap(); |
| 1330 |
e.finish().unwrap() |
| 1331 |
} |
| 1332 |
fn xz(data: &[u8]) -> Vec<u8> { |
| 1333 |
let mut e = xz2::write::XzEncoder::new(Vec::new(), 9); |
| 1334 |
e.write_all(data).unwrap(); |
| 1335 |
e.finish().unwrap() |
| 1336 |
} |
| 1337 |
fn zstd_compress(data: &[u8]) -> Vec<u8> { |
| 1338 |
zstd::encode_all(data, 19).unwrap() |
| 1339 |
} |
| 1340 |
|
| 1341 |
|
| 1342 |
|
| 1343 |
fn bomb_payload() -> Vec<u8> { |
| 1344 |
vec![0u8; 8 * 1024 * 1024] |
| 1345 |
} |
| 1346 |
|
| 1347 |
|
| 1348 |
|
| 1349 |
fn benign_payload() -> Vec<u8> { |
| 1350 |
(0..200_000u32) |
| 1351 |
.map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8) |
| 1352 |
.collect() |
| 1353 |
} |
| 1354 |
|
| 1355 |
#[test] |
| 1356 |
fn gzip_bomb_fails() { |
| 1357 |
let data = gzip(&bomb_payload()); |
| 1358 |
let result = check_archive_safety(&data, FileType::Download); |
| 1359 |
assert_eq!( |
| 1360 |
result.verdict, |
| 1361 |
LayerVerdict::Fail, |
| 1362 |
"detail: {:?}", |
| 1363 |
result.detail |
| 1364 |
); |
| 1365 |
assert!(result.detail.unwrap().to_lowercase().contains("bomb")); |
| 1366 |
} |
| 1367 |
|
| 1368 |
#[test] |
| 1369 |
fn benign_gzip_passes() { |
| 1370 |
let data = gzip(&benign_payload()); |
| 1371 |
let result = check_archive_safety(&data, FileType::Download); |
| 1372 |
assert_eq!( |
| 1373 |
result.verdict, |
| 1374 |
LayerVerdict::Pass, |
| 1375 |
"detail: {:?}", |
| 1376 |
result.detail |
| 1377 |
); |
| 1378 |
} |
| 1379 |
|
| 1380 |
#[test] |
| 1381 |
fn bzip2_bomb_fails() { |
| 1382 |
let data = bzip2_compress(&bomb_payload()); |
| 1383 |
let result = check_archive_safety(&data, FileType::Download); |
| 1384 |
assert_eq!( |
| 1385 |
result.verdict, |
| 1386 |
LayerVerdict::Fail, |
| 1387 |
"detail: {:?}", |
| 1388 |
result.detail |
| 1389 |
); |
| 1390 |
} |
| 1391 |
|
| 1392 |
#[test] |
| 1393 |
fn xz_bomb_fails() { |
| 1394 |
let data = xz(&bomb_payload()); |
| 1395 |
let result = check_archive_safety(&data, FileType::Download); |
| 1396 |
assert_eq!( |
| 1397 |
result.verdict, |
| 1398 |
LayerVerdict::Fail, |
| 1399 |
"detail: {:?}", |
| 1400 |
result.detail |
| 1401 |
); |
| 1402 |
} |
| 1403 |
|
| 1404 |
#[test] |
| 1405 |
fn zstd_bomb_fails() { |
| 1406 |
let data = zstd_compress(&bomb_payload()); |
| 1407 |
let result = check_archive_safety(&data, FileType::Download); |
| 1408 |
assert_eq!( |
| 1409 |
result.verdict, |
| 1410 |
LayerVerdict::Fail, |
| 1411 |
"detail: {:?}", |
| 1412 |
result.detail |
| 1413 |
); |
| 1414 |
} |
| 1415 |
|
| 1416 |
#[test] |
| 1417 |
fn gzip_bomb_caught_on_path_variant_too() { |
| 1418 |
let data = gzip(&bomb_payload()); |
| 1419 |
let tmp = tempfile::NamedTempFile::new().unwrap(); |
| 1420 |
std::fs::write(tmp.path(), &data).unwrap(); |
| 1421 |
let result = check_archive_safety_path(tmp.path(), FileType::Download); |
| 1422 |
assert_eq!( |
| 1423 |
result.verdict, |
| 1424 |
LayerVerdict::Fail, |
| 1425 |
"detail: {:?}", |
| 1426 |
result.detail |
| 1427 |
); |
| 1428 |
} |
| 1429 |
|
| 1430 |
#[test] |
| 1431 |
fn gzip_bomb_skipped_for_cover() { |
| 1432 |
|
| 1433 |
let data = gzip(&bomb_payload()); |
| 1434 |
let result = check_archive_safety(&data, FileType::Cover); |
| 1435 |
assert_eq!(result.verdict, LayerVerdict::Skip); |
| 1436 |
} |
| 1437 |
|
| 1438 |
|
| 1439 |
|
| 1440 |
#[test] |
| 1441 |
fn prefixed_zip_is_not_silently_skipped() { |
| 1442 |
|
| 1443 |
|
| 1444 |
|
| 1445 |
|
| 1446 |
let zip = make_zip(&[("readme.txt", b"hello")]); |
| 1447 |
let mut data = b"MZ\x90\x00 this is a self-extracting stub padding ".to_vec(); |
| 1448 |
data.extend_from_slice(&zip); |
| 1449 |
|
| 1450 |
let result = check_archive_safety(&data, FileType::Download); |
| 1451 |
assert_ne!( |
| 1452 |
result.verdict, |
| 1453 |
LayerVerdict::Skip, |
| 1454 |
"prefixed ZIP must be inspected, not skipped; got {:?}", |
| 1455 |
result.detail |
| 1456 |
); |
| 1457 |
|
| 1458 |
|
| 1459 |
let tmp = tempfile::NamedTempFile::new().unwrap(); |
| 1460 |
std::fs::write(tmp.path(), &data).unwrap(); |
| 1461 |
let path_based = check_archive_safety_path(tmp.path(), FileType::Download); |
| 1462 |
assert_ne!( |
| 1463 |
path_based.verdict, |
| 1464 |
LayerVerdict::Skip, |
| 1465 |
"detail: {:?}", |
| 1466 |
path_based.detail |
| 1467 |
); |
| 1468 |
} |
| 1469 |
|
| 1470 |
#[test] |
| 1471 |
fn prefixed_zip_bomb_fails() { |
| 1472 |
|
| 1473 |
let zeros = vec![0u8; 1024 * 1024]; |
| 1474 |
let zip = make_compressed_zip(&[("bomb.bin", &zeros)]); |
| 1475 |
let mut data = b"self-extracting stub ".to_vec(); |
| 1476 |
data.extend_from_slice(&zip); |
| 1477 |
let result = check_archive_safety(&data, FileType::Download); |
| 1478 |
assert_eq!( |
| 1479 |
result.verdict, |
| 1480 |
LayerVerdict::Fail, |
| 1481 |
"detail: {:?}", |
| 1482 |
result.detail |
| 1483 |
); |
| 1484 |
} |
| 1485 |
|
| 1486 |
#[test] |
| 1487 |
fn prefixed_7z_polyglot_rejected_for_non_download() { |
| 1488 |
|
| 1489 |
|
| 1490 |
|
| 1491 |
|
| 1492 |
let mut data = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; |
| 1493 |
data.extend_from_slice(&[0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C]); |
| 1494 |
data.extend_from_slice(&[0u8; 64]); |
| 1495 |
|
| 1496 |
|
| 1497 |
let cover = check_archive_safety(&data, FileType::Cover); |
| 1498 |
assert_eq!( |
| 1499 |
cover.verdict, |
| 1500 |
LayerVerdict::Error, |
| 1501 |
"detail: {:?}", |
| 1502 |
cover.detail |
| 1503 |
); |
| 1504 |
assert!(cover.detail.unwrap().contains("7z")); |
| 1505 |
|
| 1506 |
|
| 1507 |
let download = check_archive_safety(&data, FileType::Download); |
| 1508 |
assert_ne!( |
| 1509 |
download.verdict, |
| 1510 |
LayerVerdict::Error, |
| 1511 |
"Download must keep the ClamAV backstop, not be rejected by the container check" |
| 1512 |
); |
| 1513 |
} |
| 1514 |
|
| 1515 |
#[test] |
| 1516 |
fn prefixed_rar_polyglot_rejected_for_non_download() { |
| 1517 |
|
| 1518 |
let mut data = vec![0xFF, 0xD8, 0xFF, 0xE0]; |
| 1519 |
data.extend_from_slice(&[0x52, 0x61, 0x72, 0x21, 0x1A, 0x07]); |
| 1520 |
data.extend_from_slice(&[0u8; 64]); |
| 1521 |
let cover = check_archive_safety(&data, FileType::Cover); |
| 1522 |
assert_eq!( |
| 1523 |
cover.verdict, |
| 1524 |
LayerVerdict::Error, |
| 1525 |
"detail: {:?}", |
| 1526 |
cover.detail |
| 1527 |
); |
| 1528 |
assert!(cover.detail.unwrap().contains("RAR")); |
| 1529 |
} |
| 1530 |
} |
| 1531 |
|