HIGH zip slipchi

Zip Slip in Chi

How Zip Slip Manifests in Chi

Zip Slip vulnerabilities in Chi-based APIs typically emerge when file upload endpoints process untrusted ZIP archives without proper path validation. In Chi applications, this manifests when handlers accept multipart form data containing ZIP files and extract them using Go's standard library without validating the extracted file paths.

A common Chi-specific pattern involves middleware that processes uploads before reaching the main handler. When a ZIP file is uploaded through a Chi endpoint like /upload, the extraction logic might inadvertently create files outside the intended directory. The vulnerability occurs when the ZIP archive contains entries with relative paths like ../../etc/passwd or absolute paths like /etc/passwd.

Consider this Chi handler that processes ZIP uploads:

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    file, _, err := r.FormFile("file")
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer file.Close()

    zipReader, err := zip.NewReader(file, int64(fileSize))
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    for _, f := range zipReader.File {
        rc, err := f.Open()
        if err != nil {
            continue
        }
        defer rc.Close()

        extractedPath := filepath.Join("/var/uploads", f.Name)
        os.MkdirAll(filepath.Dir(extractedPath), 0755)
        
        outFile, err := os.Create(extractedPath)
        if err != nil {
            continue
        }
        defer outFile.Close()

        io.Copy(outFile, rc)
    }
    w.Write([]byte("Upload successful"))
}

The critical flaw is using f.Name directly without validation. An attacker can craft a ZIP with ../../../../../etc/passwd as a filename, and the filepath.Join operation will resolve to a path outside /var/uploads. This allows arbitrary file write anywhere the Chi process has permissions, potentially overwriting critical system files or application code.

Another Chi-specific manifestation occurs when using middleware for authentication or logging that processes file uploads. If middleware extracts ZIP contents for scanning or metadata collection without proper validation, the vulnerability exists before the main handler logic executes. This creates a window where malicious files can be written to the filesystem before any security checks occur.

Chi-Specific Detection

Detecting Zip Slip in Chi applications requires both static analysis and runtime scanning. For static detection, examine all handlers that process file uploads for ZIP extraction patterns. Look for these red flags in your Chi codebase:

  • Direct use of zip.NewReader without path validation
  • Concatenation of user-controlled paths with filepath.Join
  • Extraction to directories with insufficient permissions or outside application boundaries
  • Missing validation of zip.File.FileInfo().IsDir() before extraction

Runtime detection with middleBrick provides comprehensive coverage for Chi APIs. The scanner examines the unauthenticated attack surface by submitting crafted ZIP payloads to upload endpoints. middleBrick tests for Zip Slip by including files with various path traversal patterns:

../../../../../tmp/test.txt
/etc/passwd
/var/log/auth.log
../../../bin/ls
.././.././../tmp/evil.sh

The scanner verifies whether these files are written outside the intended directory by checking for their existence post-extraction or monitoring filesystem changes during the scan. middleBrick's parallel security checks include specific Zip Slip detection that identifies when extracted files escape the designated upload directory.

For Chi applications, middleBrick also examines OpenAPI specifications to understand the expected file handling behavior. If your Chi API documents an upload endpoint that accepts ZIP files, the scanner correlates this with runtime findings to provide context-aware risk assessment. The tool checks whether the documented behavior matches the actual implementation and flags discrepancies that might indicate security gaps.

Additional detection methods include:

  • Logging all file operations during ZIP extraction to identify suspicious path resolutions
  • Using filesystem monitoring to alert on writes outside designated directories
  • Implementing a security proxy that intercepts and validates ZIP contents before they reach your Chi application

middleBrick's LLM/AI security checks are particularly relevant if your Chi application processes ZIP files containing AI model artifacts or configuration files that might be consumed by language models. The scanner can detect if extracted files contain system prompts or model weights that could be exploited for prompt injection attacks.

Chi-Specific Remediation

Securing Chi applications against Zip Slip requires validating extracted file paths before any filesystem operations. The most effective approach is to implement a path sanitization function that rejects any ZIP entry attempting directory traversal:

func validateZipEntry(entry *zip.File, basePath string) (string, error) {
    // Reject absolute paths
    if filepath.IsAbs(entry.Name) {
        return "", fmt.Errorf("absolute path in ZIP entry")
    }

    // Resolve the target path
    targetPath := filepath.Join(basePath, entry.Name)
    
    // Clean the path and check if it's still within base
    cleanPath, err := filepath.Abs(targetPath)
    if err != nil {
        return "", err
    }
    
    baseDir, err := filepath.Abs(basePath)
    if err != nil {
        return "", err
    }
    
    // Ensure the resolved path is within the base directory
    if !strings.HasPrefix(cleanPath, baseDir+string(filepath.Separator)) {
        return "", fmt.Errorf("path traversal detected: %s", entry.Name)
    }
    
    return cleanPath, nil
}

Integrate this validation into your Chi handler:

func secureUploadHandler(w http.ResponseWriter, r *http.Request) {
    file, _, err := r.FormFile("file")
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer file.Close()

    zipReader, err := zip.NewReader(file, int64(fileSize))
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    basePath := "/var/uploads/"
    
    for _, f := range zipReader.File {
        if f.FileInfo().IsDir() {
            continue
        }

        targetPath, err := validateZipEntry(f, basePath)
        if err != nil {
            http.Error(w, "Invalid file in archive: "+err.Error(), http.StatusBadRequest)
            return
        }

        rc, err := f.Open()
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer rc.Close()

        os.MkdirAll(filepath.Dir(targetPath), 0755)
        
        outFile, err := os.Create(targetPath)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer outFile.Close()

        io.Copy(outFile, rc)
    }
    w.Write([]byte("Upload successful"))
}

For Chi middleware that processes uploads, implement the same validation before any extraction occurs. This ensures that even if middleware handles the ZIP files, the security check is applied consistently:

func zipValidationMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Method == http.MethodPost {
            file, _, err := r.FormFile("file")
            if err == nil {
                // Peek at the first few bytes to check if it's a ZIP
                header := make([]byte, 4)
                file.Read(header)
                file.Seek(0, 0) // Reset for next reader
                
                if header[0] == 0x50 && header[1] == 0x4B && header[2] == 0x03 && header[3] == 0x04 {
                    // ZIP signature detected, validate
                    zipReader, err := zip.NewReader(file, int64(fileSize))
                    if err != nil {
                        http.Error(w, "Invalid ZIP file", http.StatusBadRequest)
                        return
                    }
                    
                    basePath := "/var/uploads/"
                    for _, f := range zipReader.File {
                        if _, err := validateZipEntry(f, basePath); err != nil {
                            http.Error(w, "Invalid file in archive: "+err.Error(), http.StatusBadRequest)
                            return
                        }
                    }
                    
                    // Reset file for next handler
                    file.Seek(0, 0)
                }
            }
        }
        next.ServeHTTP(w, r)
    })
}

Additional Chi-specific hardening includes setting restrictive permissions on the upload directory, implementing file type validation beyond just ZIP signatures, and using a dedicated user account with minimal filesystem permissions for the Chi process. Consider using a library like github.com/mholt/archiver/v4 which provides safer extraction with built-in path validation.

middleBrick's continuous monitoring in the Pro plan can help verify that these remediations remain effective over time. The scanner will periodically test your Chi endpoints with updated Zip Slip payloads, ensuring that security fixes haven't been inadvertently broken by code changes or library updates.

Frequently Asked Questions

How can I test if my Chi API is vulnerable to Zip Slip?
Create a test ZIP file with known malicious paths like ../../../../../tmp/test.txt and attempt to upload it to your Chi endpoint. If the file appears outside your intended upload directory, you have a vulnerability. For comprehensive testing, use middleBrick which automatically tests for Zip Slip and other file-based attacks without requiring you to craft payloads manually.
Does Zip Slip only affect file uploads, or can it occur elsewhere in Chi applications?
While file uploads are the most common vector, Zip Slip can also occur when processing ZIP archives from other sources like API responses, configuration files, or data exports. Any Chi endpoint that extracts ZIP contents without proper path validation is potentially vulnerable. This includes background workers, scheduled jobs, or middleware that processes archived data.