mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Add check to verify extracted zip paths are within project directory.
This commit is contained in:
1 parent
5e352e60e9
commit
ce4a602270
3 files changed
+151
-11
No files matched your search
@@ -361,6 +361,83 @@ describe('ProjectsManager', () => {
|
||||
expect(project.name).toBe('new-project');
|
||||
expect(project.id).toBe('new-project');
|
||||
});
|
||||
|
||||
it('should prevent zip slip attacks during import', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock the git methods
|
||||
const mockGit = {
|
||||
init: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
add: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
getConfig: vi.fn(),
|
||||
getAllFiles: vi.fn().mockResolvedValue([]),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Create a mock ZIP file that would try to escape the project directory
|
||||
const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' });
|
||||
|
||||
// Mock JSZip to simulate a malicious ZIP with path traversal
|
||||
const JSZip = await import('jszip');
|
||||
|
||||
const mockLoadAsync = vi.fn().mockResolvedValue({
|
||||
files: {
|
||||
'../../../etc/passwd': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||
},
|
||||
'../../outside.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
'safe-file.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync);
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new ArrayBuffer(0)),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Spy on console.warn to check for security warnings
|
||||
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
try {
|
||||
// Import the malicious ZIP
|
||||
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||
|
||||
// Should have completed successfully (safe files extracted)
|
||||
expect(project).toBeDefined();
|
||||
|
||||
// Should have logged a security warning about skipped files
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Skipped 2 files due to security concerns'),
|
||||
['../../../etc/passwd', '../../outside.txt']
|
||||
);
|
||||
|
||||
// Verify that only safe files would be written (check writeFile calls)
|
||||
const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || [];
|
||||
const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) =>
|
||||
call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt')
|
||||
);
|
||||
expect(maliciousPaths).toHaveLength(0);
|
||||
|
||||
} finally {
|
||||
// Restore mocks
|
||||
consoleSpy.mockRestore();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
|
||||
+72
-10
@@ -154,32 +154,41 @@ export class ProjectsManager {
|
||||
const arrayBuffer = await zipFile.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
|
||||
// Extract all files from the zip
|
||||
const files = Object.keys(zip.files);
|
||||
// Extract all files from the zip with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const filePath of files) {
|
||||
const zipEntry = zip.files[filePath];
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
// Validate the extraction path is within the project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip directories (they end with / in JSZip)
|
||||
if (zipEntry.dir) {
|
||||
// Create the directory structure
|
||||
const dirPath = `${projectPath}/${filePath}`;
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
await this.fs.mkdir(extractPath, { recursive: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract file content
|
||||
const content = await zipEntry.async('uint8array');
|
||||
const fullPath = `${projectPath}/${filePath}`;
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = fullPath.split('/').slice(0, -1).join('/');
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(fullPath, content);
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
@@ -580,4 +589,57 @@ export class ProjectsManager {
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe path join that normalizes the result to prevent directory traversal
|
||||
*/
|
||||
private join(...paths: string[]): string {
|
||||
// Simple path joining with normalization
|
||||
const joined = paths.join('/').replace(/\/+/g, '/');
|
||||
|
||||
// Normalize path separators and resolve .. and . components
|
||||
const parts = joined.split('/').filter(part => part !== '');
|
||||
const normalized: string[] = [];
|
||||
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
normalized.pop();
|
||||
} else if (part !== '.') {
|
||||
normalized.push(part);
|
||||
}
|
||||
}
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is within the project directory
|
||||
*/
|
||||
private isPathWithinProject(extractPath: string, projectPath: string): boolean {
|
||||
// Normalize both paths
|
||||
const normalizedExtractPath = this.normalize(extractPath);
|
||||
const normalizedProjectPath = this.normalize(projectPath);
|
||||
|
||||
// Check if the extract path starts with the project path
|
||||
return normalizedExtractPath.startsWith(normalizedProjectPath + '/') ||
|
||||
normalizedExtractPath === normalizedProjectPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a path by resolving . and .. components
|
||||
*/
|
||||
private normalize(path: string): string {
|
||||
const parts = path.split('/').filter(part => part !== '');
|
||||
const normalized: string[] = [];
|
||||
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
normalized.pop();
|
||||
} else if (part !== '.') {
|
||||
normalized.push(part);
|
||||
}
|
||||
}
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -261,12 +261,13 @@ export default function Index() {
|
||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
checkForKeyFailure(error) ||
|
||||
if (!checkForKeyFailure(error)) {
|
||||
toast({
|
||||
title: "Project Creation Failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user