Zip Slip archive path traversal

Zip Slip archive path traversal

Description

When creating files from ZIP entry names, enforce the extraction directory’s boundary using the target operating system’s path rules.

Potential impact

Overwriting configuration, web content, or executables within the process’s permissions can interrupt service or change code that later runs.

Remediation

Extract only the files you need into a new private directory. For a flat archive, accept single-component filenames and reject absolute paths, parent traversal, directories, and links. Create files exclusively and handle open, copy, and close errors. Limit actual expanded bytes and entry count.

Examples

The first excerpt assumes dest and ZIP entry file are available. The second assumes that other code running as the same account cannot change its temporary directory. Size limits are omitted.

Before

go
_, _ = os.Create(filepath.Join(dest, file.Name))

After

go
package example

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
    "path/filepath"
)

func extractFlat(r *zip.Reader) (root string, err error) {
    root, err = os.MkdirTemp("", "xeize-unzip-")
    if err != nil {
        return "", err
    }
    createdRoot := root
    defer func() {
        if err != nil {
            _ = os.RemoveAll(createdRoot)
        }
    }()

    for _, file := range r.File {
        if !file.Mode().IsRegular() {
            return "", fmt.Errorf("unsupported archive entry: %q", file.Name)
        }

        name := filepath.Clean(file.Name)
        if name != file.Name || filepath.IsAbs(name) || name == "." || name == ".." ||
            name != filepath.Base(name) {
            return "", fmt.Errorf("invalid archive path: %q", file.Name)
        }

        in, err := file.Open()
        if err != nil {
            return "", err
        }
        out, err := os.OpenFile(filepath.Join(root, name),
            os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
        if err != nil {
            in.Close()
            return "", err
        }

        _, copyErr := io.Copy(out, in)
        closeOutErr := out.Close()
        closeInErr := in.Close()
        if copyErr != nil {
            return "", copyErr
        }
        if closeOutErr != nil {
            return "", closeOutErr
        }
        if closeInErr != nil {
            return "", closeInErr
        }
    }
    return root, nil
}

After file.Mode().IsRegular() and the filename checks pass, O_EXCL allows only new files. The function attempts to remove the directory on error. The caller cleans it up after success.

References