Zip Slip in Firestore
How Zip Slip Manifests in Firestore
Zip Slip in Firestore environments typically emerges when applications process uploaded archives containing file paths that traverse directory boundaries. Unlike traditional file systems where Zip Slip directly writes to the filesystem, Firestore-specific manifestations occur through indirect paths that ultimately lead to data exfiltration or unauthorized access.
The core vulnerability pattern in Firestore applications involves processing ZIP archives where embedded file paths contain ../ sequences. When these archives are processed without proper path validation, attackers can craft payloads that reference paths outside intended directories. In Firestore contexts, this often manifests when applications extract archive contents to temporary storage before uploading to Firestore collections, or when processing file metadata that references external paths.
A common Firestore Zip Slip pattern occurs in document processing workflows. Consider an application that accepts document uploads, extracts ZIP contents to a temporary directory, then stores extracted files in Firestore Storage or references them in Firestore documents. Without path validation, an attacker can upload a ZIP containing ../../etc/passwd or similar traversal sequences. The application extracts these files, potentially exposing sensitive system files if the extraction occurs on a server with filesystem access.
Another manifestation involves metadata processing. Applications often extract ZIP metadata (file names, paths, timestamps) and store this information in Firestore documents. Attackers can embed malicious path information in ZIP metadata that, when processed and displayed in application interfaces, leads to information disclosure or client-side attacks.
Firestore-specific Zip Slip also appears in backup and restore operations. Applications that allow users to download Firestore data as ZIP archives, modify them locally, then re-upload for restoration become vulnerable if the restore process doesn't validate extracted paths. An attacker could modify the ZIP to include traversal sequences that overwrite unintended documents or collections during restoration.
The serverless nature of many Firestore applications adds complexity. When ZIP processing occurs in Cloud Functions or similar serverless environments, the extracted files might be processed by other services or stored in ways that create indirect attack surfaces. For example, a function that extracts ZIP contents to Cloud Storage before processing could be exploited if the extraction logic doesn't validate paths.
Real-world Firestore Zip Slip scenarios often involve document conversion services. An application accepts ZIP archives containing documents, extracts them, converts to PDF or other formats, then stores results in Firestore. Without path validation, traversal sequences in file names could lead to processing unintended files or exposing system information during the conversion process.
API endpoints that accept ZIP uploads for batch processing represent another attack vector. These endpoints typically extract contents to temporary storage, process individual files, then clean up. Attackers can craft ZIPs with traversal sequences that cause the extraction to overwrite critical files or expose sensitive information during processing.
Firestore-Specific Detection
Detecting Zip Slip vulnerabilities in Firestore applications requires a multi-layered approach combining static analysis, dynamic testing, and runtime monitoring. The detection strategy must account for Firestore's unique architecture and common usage patterns.
Static code analysis should focus on ZIP processing logic. Look for patterns where applications extract ZIP contents without validating file paths. In Firestore applications, this often appears in Cloud Functions, API endpoints, or backend services that handle file uploads. Key indicators include calls to ZIP extraction libraries (SharpZipLib, System.IO.Compression, etc.) without subsequent path validation.
Dynamic testing involves submitting crafted ZIP payloads to application endpoints and observing behavior. Effective test payloads include:
files/
└── evil.txt
└── ..
└── ..
└── target.txtWhen testing Firestore applications, monitor for successful extraction of files to unexpected locations, error messages that reveal system paths, or application behavior changes indicating path traversal.
middleBrick's API security scanning includes specialized Zip Slip detection for Firestore applications. The scanner examines API endpoints that accept file uploads, analyzing request handling for path traversal vulnerabilities. For Firestore-specific endpoints, middleBrick tests ZIP upload functionality by submitting crafted archives containing traversal sequences and monitoring responses.
The scanner's detection methodology includes:
- Path validation analysis: examining how applications handle file paths from ZIP archives
- Directory traversal testing: submitting ZIPs with
../sequences and observing extraction behavior - Metadata extraction testing: analyzing how applications process and store file metadata from archives
- Cross-reference analysis: comparing API specifications with observed behavior to identify mismatches
For Firestore applications, middleBrick's scanning extends to Firestore-specific patterns. The scanner tests endpoints that handle document uploads, batch processing, and backup/restore operations. It examines how applications process ZIP contents before storing data in Firestore collections or Cloud Storage.
Runtime monitoring complements scanning by detecting Zip Slip attempts in production. Implement logging for ZIP processing operations, monitoring for unusual file paths, extraction errors, or access patterns that suggest traversal attempts. Cloud Functions logs can reveal when ZIP processing occurs and whether path validation is functioning correctly.
Automated testing in CI/CD pipelines using middleBrick's GitHub Action provides continuous Zip Slip detection. Configure the action to scan API endpoints whenever code changes, ensuring new ZIP processing functionality doesn't introduce vulnerabilities. The action can fail builds if Zip Slip risks are detected, preventing vulnerable code from reaching production.
Compliance scanning with middleBrick maps Zip Slip findings to relevant standards. OWASP API Top 10 includes path traversal under API5 (Broken Function Level Authorization), while PCI-DSS and SOC2 compliance frameworks require proper input validation. middleBrick's reports show how Zip Slip vulnerabilities impact compliance status.
For comprehensive detection, combine multiple approaches: static analysis of codebases, dynamic testing of endpoints, runtime monitoring, and automated scanning with middleBrick. This layered strategy ensures Zip Slip vulnerabilities are identified regardless of how they manifest in your Firestore application.
Firestore-Specific Remediation
Remediating Zip Slip vulnerabilities in Firestore applications requires implementing robust path validation and secure ZIP processing practices. The remediation strategy must address both the immediate vulnerability and underlying design patterns that enable exploitation.
Path validation is the cornerstone of Zip Slip remediation. Implement strict validation of all file paths extracted from ZIP archives using the following Node.js example for Firestore applications:
const path = require('path');
function validateZipPath(archivePath, intendedDirectory) {
const resolvedPath = path.resolve(intendedDirectory, archivePath);
const relativePath = path.relative(intendedDirectory, resolvedPath);
// Check for path traversal
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
throw new Error('Path traversal detected');
}
return resolvedPath;
}In Firestore contexts, apply this validation before extracting ZIP contents to temporary storage or processing files for upload to Cloud Storage. The validation ensures that all extracted paths remain within the intended directory structure.
For Cloud Functions processing ZIP uploads, implement a secure extraction pattern:
const admZip = require('adm-zip');
const { Storage } = require('@google-cloud/storage');
exports.processZipUpload = async (req, res) => {
try {
const zipBuffer = req.body;
const zip = new admZip(zipBuffer);
// Create temporary directory
const tempDir = `/tmp/zip-processing-${Date.now()}`;
await fs.promises.mkdir(tempDir);
// Extract with path validation
const zipEntries = zip.getEntries();
for (const entry of zipEntries) {
const validatedPath = validateZipPath(entry.entryName, tempDir);
// Only process files (skip directories)
if (!entry.isDirectory) {
await fs.promises.mkdir(path.dirname(validatedPath), { recursive: true });
await fs.promises.writeFile(validatedPath, entry.getData());
}
}
// Process validated files
await processValidatedFiles(tempDir);
// Clean up
await fs.promises.rmdir(tempDir, { recursive: true });
res.status(200).send('Processing complete');
} catch (error) {
console.error('ZIP processing error:', error);
res.status(400).send('Invalid ZIP content');
}
};This pattern validates each file path before extraction, processes only validated files, and includes proper cleanup to prevent resource exhaustion.
For Firestore document processing workflows, implement metadata validation:
function validateDocumentMetadata(metadata) {
const { fileName, filePath, fileSize } = metadata;
// Validate file name (no traversal sequences)
if (fileName.includes('..') || fileName.includes('/') || fileName.includes('\')) {
throw new Error('Invalid file name');
}
// Validate file path if provided
if (filePath) {
const sanitizedPath = path.normalize(filePath);
if (sanitizedPath !== filePath) {
throw new Error('Invalid file path');
}
}
// Validate file size limits
const maxSize = 10 * 1024 * 1024; // 10MB limit
if (fileSize > maxSize) {
throw new Error('File size exceeds limit');
}
return true;
}Apply this validation when processing ZIP metadata before storing in Firestore documents. This prevents malicious path information from entering your database.
For backup and restore operations, implement atomic processing with validation:
async function safeRestore(zipBuffer, firestore) {
const tempDir = `/tmp/restore-${Date.now()}`;
try {
// Extract with validation
const zip = new admZip(zipBuffer);
const entries = zip.getEntries();
// First pass: validate all paths
const validatedFiles = [];
for (const entry of entries) {
if (!entry.isDirectory) {
const validatedPath = validateZipPath(entry.entryName, tempDir);
validatedFiles.push({ entry, validatedPath });
}
}
// Second pass: extract validated files
for (const { entry, validatedPath } of validatedFiles) {
await fs.promises.mkdir(path.dirname(validatedPath), { recursive: true });
await fs.promises.writeFile(validatedPath, entry.getData());
}
// Process restore (atomic operation)
await firestore.runTransaction(async (transaction) => {
for (const file of validatedFiles) {
const documentPath = getDocumentPathFromFile(file.validatedPath);
const documentData = await parseDocumentFile(file.validatedPath);
transaction.set(
firestore.doc(documentPath),
documentData,
{ merge: true }
);
}
});
} catch (error) {
console.error('Restore failed:', error);
throw error;
} finally {
// Cleanup
await fs.promises.rmdir(tempDir, { recursive: true });
}
}This approach validates all paths before any extraction occurs, processes files atomically to prevent partial restores, and includes cleanup to maintain security.
For comprehensive remediation, combine these technical fixes with organizational practices: implement code reviews focusing on file processing logic, add Zip Slip detection to automated testing with middleBrick's CLI tool, and establish incident response procedures for path traversal attempts.
Frequently Asked Questions
How does Zip Slip in Firestore differ from traditional file system Zip Slip?
Traditional Zip Slip directly writes files to the filesystem, potentially overwriting system files or exposing sensitive data. Firestore Zip Slip manifests indirectly through path traversal in ZIP processing workflows, metadata handling, or backup operations. Instead of direct filesystem access, attackers exploit the application's processing logic to cause unintended behavior in Firestore data storage, Cloud Storage operations, or document processing pipelines.
Can middleBrick detect Zip Slip vulnerabilities in Firestore applications?
Yes, middleBrick's API security scanner includes specialized Zip Slip detection for Firestore applications. The scanner tests API endpoints that accept ZIP uploads by submitting crafted archives containing path traversal sequences. It analyzes how applications handle file paths, extract contents, and process ZIP metadata. middleBrick's scanning identifies vulnerabilities without requiring credentials or agents, providing actionable findings with severity levels and remediation guidance specific to Firestore contexts.