File size: 3,032 Bytes
4fea3ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | const fs = require('fs');
const path = require('path');
const { SECURITY_CONFIG, PathValidationError, SecurityError } = require('./security-config');
// Validate Input Path
function validateInput(target) {
if (!target || typeof target !== 'string') {
throw new PathValidationError('Invalid target path', target, 'INVALID_TYPE');
}
if (target.length > SECURITY_CONFIG.MAX_PATH_LENGTH) {
throw new PathValidationError('Path too long', target, 'PATH_TOO_LONG');
}
// Check for dangerous characters (excluding : for Windows drives)
const dangerousChars = /[<>"|?*\x00-\x1f]/;
if (dangerousChars.test(target)) {
throw new PathValidationError('Dangerous characters in path', target, 'DANGEROUS_CHARS');
}
return true;
}
// Check Path Safety
function isPathSafe(targetPath) {
const normalizedPath = path.resolve(targetPath);
// Check forbidden paths
for (const forbiddenPattern of SECURITY_CONFIG.FORBIDDEN_PATHS) {
if (forbiddenPattern.test(normalizedPath)) {
throw new SecurityError(
`Access to system directories is not allowed: ${normalizedPath}`,
targetPath,
'SYSTEM_DIR_ACCESS'
);
}
}
// Check path traversal
if (normalizedPath.includes('..')) {
throw new SecurityError('Path traversal is not allowed', targetPath, 'PATH_TRAVERSAL');
}
return true;
}
// Sanitize Path
function sanitizePath(inputPath) {
const normalizedPath = path.normalize(inputPath);
// Check for null bytes
if (normalizedPath.includes('\x00')) {
throw new PathValidationError('Null bytes in path are not allowed', inputPath, 'NULL_BYTES');
}
return normalizedPath;
}
// Check File Permissions
function checkFilePermissions(filePath, requireWrite = false) {
try {
// Check read permission
fs.accessSync(filePath, fs.constants.R_OK);
// Check write permission if required
if (requireWrite) {
fs.accessSync(filePath, fs.constants.W_OK);
}
return true;
} catch (error) {
throw new SecurityError(`Permission denied: ${filePath}`, filePath, 'PERMISSION_DENIED');
}
}
// Validate File Extension
function isAllowedExtension(filePath) {
const ext = path.extname(filePath).toLowerCase();
return SECURITY_CONFIG.ALLOWED_EXTENSIONS.includes(ext);
}
// Check File Size
function checkFileSize(filePath) {
const stats = fs.statSync(filePath);
if (stats.size > SECURITY_CONFIG.MAX_FILE_SIZE) {
throw new SecurityError(
`File too large (${stats.size} bytes, max ${SECURITY_CONFIG.MAX_FILE_SIZE})`,
filePath,
'FILE_TOO_LARGE'
);
}
return stats;
}
module.exports = {
validateInput,
isPathSafe,
sanitizePath,
checkFilePermissions,
isAllowedExtension,
checkFileSize
};
|