HIGH zip slipdocker

Zip Slip on Docker

How Zip Slip Manifests in Docker

Zip Slip in Docker environments exploits the same fundamental vulnerability as traditional Zip Slip attacks, but with Docker-specific attack vectors and consequences. The vulnerability occurs when Docker containers process maliciously crafted archive files that contain path traversal sequences, allowing attackers to overwrite files outside the intended extraction directory.

In Docker contexts, Zip Slip attacks typically target container build processes, runtime file extraction, and CI/CD pipelines. A common scenario involves Dockerfile COPY or ADD instructions that extract archives, or application code within containers that processes user-supplied zip files. The Docker daemon itself doesn't inherently validate archive contents, making it vulnerable to path traversal attacks when processing untrusted input.

Consider a Dockerfile that copies and extracts a zip archive:

FROM alpine:3.18
WORKDIR /app
COPY malicious.zip /tmp/
RUN unzip /tmp/malicious.zip -d /app

If malicious.zip contains files with paths like ../../etc/passwd or ../../../../../../tmp/evil.sh, the unzip command will extract these files outside the intended /app directory. This can overwrite critical system files, inject malicious scripts, or replace configuration files that the container relies on during runtime.

Another Docker-specific attack pattern involves multi-stage builds where archives are processed in intermediate stages. An attacker could craft a zip file that, when extracted in an early stage, places malicious files in locations that persist to final stages or affect build-time scripts. For example:

FROM node:18-alpine AS builder
WORKDIR /build
COPY package.json .
COPY malicious.zip .
RUN unzip malicious.zip
RUN npm install

If the malicious zip contains a package.json with a postinstall script, this script would execute during the npm install phase, potentially giving the attacker code execution during the build process.

Runtime Zip Slip attacks in Docker often involve applications that accept file uploads and process archives. A Node.js application running in a Docker container might use the adm-zip library to extract user-provided archives:

const AdmZip = require('adm-zip');
app.post('/upload', (req, res) => {
  const zip = new AdmZip(req.files.archive.data);
  zip.extractAllTo('/app/uploads', true);
});

Without proper path validation, this code allows path traversal attacks. An attacker could upload a zip containing ../../../../../etc/shadow, which would be extracted to the host system's shadow file location, potentially exposing sensitive password hashes.

Docker's layered filesystem architecture adds another dimension to Zip Slip attacks. When extracting archives to mounted volumes or bind mounts, path traversal can escape the container's filesystem boundaries and affect the host system or other containers sharing the same volume. This is particularly dangerous in development environments where containers are often run with elevated privileges or access to host directories.

Supply chain attacks through Docker Hub or other registries can also leverage Zip Slip. If a malicious actor uploads a Docker image containing a zip file with path traversal payloads, users pulling and building that image could inadvertently execute the attack during the build process. This highlights the importance of scanning both Docker images and the archives they contain.

Docker-Specific Detection

Detecting Zip Slip vulnerabilities in Docker environments requires a multi-layered approach that examines both the container build process and runtime behavior. The most effective detection strategy combines static analysis of Dockerfiles and application code with dynamic scanning of running containers.

Static analysis of Dockerfiles should focus on identifying commands that extract archives without proper validation. Look for patterns like:

RUN unzip -q file.zip -d /target
RUN tar -xzf archive.tar.gz -C /destination
COPY --from=stage archive.zip /tmp/
ADD http://example.com/archive.zip /tmp/

Each of these commands represents a potential Zip Slip vulnerability if the source archive is untrusted. The ADD instruction is particularly dangerous because it automatically extracts archives, and when combined with remote URLs, it can introduce both Zip Slip and supply chain risks.

Application code analysis should examine libraries and functions that handle archive extraction. In Node.js applications, search for:

const AdmZip = require('adm-zip');
const unzip = require('unzip');
const yauzl = require('yauzl');
const archiver = require('archiver');

Look for usage patterns where these libraries extract files without path validation. For example:

// Vulnerable pattern
zip.extractAllTo(destination, true);
// Safer pattern with validation
zip.getEntries().forEach(entry => {
  const entryName = entry.entryName;
  if (entryName.includes('..') || !entryName.startsWith('safe-prefix/')) {
    throw new Error('Invalid path');
  }
  entry.extract(destination);
});

middleBrick's Docker-specific scanning capabilities can automatically detect these patterns by analyzing both the container's runtime behavior and its configuration. The scanner examines Dockerfile contents, identifies archive extraction commands, and analyzes application code for vulnerable archive handling patterns. It also tests the container's actual behavior by attempting controlled path traversal attacks in a sandboxed environment.

Runtime detection involves monitoring container file system operations during archive extraction. Tools like auditd or Docker's built-in security features can log file access patterns that indicate path traversal attempts. Look for processes attempting to write to directories outside their working directory or accessing sensitive system paths.

Supply chain detection is critical for Docker environments. middleBrick scans Docker images from registries for known malicious patterns, including zip files with suspicious path structures. The scanner can identify archives containing files with path traversal sequences before they're ever extracted, preventing supply chain attacks.

CI/CD pipeline integration provides automated detection throughout the development lifecycle. middleBrick's GitHub Action can scan Docker images and Dockerfiles as part of the build process, failing builds that contain Zip Slip vulnerabilities. This ensures that vulnerable containers never make it to production.

Network-based detection can identify Zip Slip attacks in progress by monitoring for unusual file access patterns. If a container suddenly attempts to read or write to system directories like /etc, /proc, or /root, this could indicate a successful Zip Slip attack. Docker's built-in logging and monitoring tools, combined with external security information and event management (SIEM) systems, can provide real-time alerts for suspicious activity.

Docker-Specific Remediation

Remediating Zip Slip vulnerabilities in Docker environments requires a defense-in-depth approach that combines secure coding practices, Docker configuration hardening, and runtime protections. The most effective strategy addresses the vulnerability at multiple layers of the container stack.

Start with secure Dockerfile practices. Replace vulnerable archive extraction commands with validated alternatives:

FROM alpine:3.18
WORKDIR /app
# Instead of: COPY malicious.zip /tmp/ && unzip /tmp/malicious.zip -d /app
# Use a safer approach:
RUN wget -O /tmp/safe-archive.zip https://example.com/safe-archive.zip && \
    unzip -l /tmp/safe-archive.zip | grep -E "(^|/)\.\./" && \
    if [ $? -eq 0 ]; then echo "Path traversal detected"; exit 1; fi && \
    unzip /tmp/safe-archive.zip -d /app

This pattern uses unzip -l to list archive contents before extraction and checks for path traversal patterns using grep. If suspicious paths are found, the build fails before any files are extracted.

For Node.js applications, use libraries with built-in path validation or implement custom validation:

const AdmZip = require('adm-zip');
const path = require('path');
const fs = require('fs');

function safeExtract(zip, destination) {
  const entries = zip.getEntries();
  entries.forEach(entry => {
    const entryName = entry.entryName;
    // Validate path: no traversal, no absolute paths, within destination
    if (entryName.includes('..') || 
        path.isAbsolute(entryName) || 
        !entryName.startsWith('safe-prefix/')) {
      throw new Error(`Invalid path: ${entryName}`);
    }
    
    // Resolve to absolute path and ensure it's within destination
    const fullPath = path.resolve(destination, entryName);
    if (!fullPath.startsWith(path.resolve(destination))) {
      throw new Error(`Path traversal: ${entryName}`);
    }
    
    // Create directory structure safely
    const dir = path.dirname(fullPath);
    fs.mkdirSync(dir, { recursive: true });
    
    // Extract file
    entry.extract(fullPath);
  });
}

This function validates each entry before extraction, ensuring paths cannot escape the intended directory and that no absolute paths are allowed.

Docker's security features can provide additional protection. Run containers with the --read-only flag to prevent file system modifications:

docker run --read-only -v /tmp:/tmp:rw myapp

This makes the container's root filesystem read-only while allowing specific writable directories through bind mounts. Combined with user namespaces (--user flag), this limits the impact of successful Zip Slip attacks.

Implement content trust and image signing to prevent supply chain attacks. Docker Content Trust ensures that only signed images from trusted sources are pulled and run:

export DOCKER_CONTENT_TRUST=1
docker pull myregistry/myapp:latest

This prevents attackers from replacing legitimate images with malicious ones containing Zip Slip payloads.

For CI/CD environments, integrate middleBrick's scanning capabilities to automatically detect Zip Slip vulnerabilities before deployment:

# GitHub Action example
name: Security Scan
on: [push, pull_request]
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Scan Dockerfile
      run: |
        npm install -g middlebrick
        middlebrick scan --dockerfile Dockerfile
    - name: Scan application code
      run: |
        middlebrick scan --path ./src --type node

This workflow scans both the Dockerfile and application source code for Zip Slip vulnerabilities on every code change.

Runtime monitoring with Docker's security features provides ongoing protection. Use Docker Bench Security or similar tools to audit container configurations and identify potential Zip Slip attack vectors. Monitor container logs for unusual file access patterns and set up alerts for suspicious activity.

Finally, implement a comprehensive patch management strategy. Keep all base images, libraries, and tools up to date to benefit from security fixes. Regularly scan your Docker images with middleBrick to identify newly discovered vulnerabilities, including Zip Slip variants that may have been introduced through updated dependencies.

Frequently Asked Questions

Can Zip Slip attacks in Docker containers affect the host system?

Yes, Zip Slip attacks can affect the host system when containers are run with elevated privileges or when extracting archives to mounted volumes. If a container has write access to host directories through bind mounts, path traversal in archive extraction can overwrite host files. Running containers as root (--user root) or with the --privileged flag significantly increases this risk. Always use the principle of least privilege and avoid mounting sensitive host directories into containers.

How does middleBrick detect Zip Slip vulnerabilities in Docker environments?

middleBrick uses a multi-layered approach to detect Zip Slip in Docker contexts. It statically analyzes Dockerfiles to identify vulnerable archive extraction commands, examines application code for unsafe archive handling patterns, and performs dynamic scanning by testing containers with controlled path traversal attempts. The scanner also examines Docker images from registries for malicious archive contents before they're ever extracted. middleBrick's GitHub Action can integrate this scanning into CI/CD pipelines, automatically failing builds that contain Zip Slip vulnerabilities.