3 Commits

Author SHA1 Message Date
a8af857cd3 security: fix vulnerabilities and harden code (2026-03-12)
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
Path traversal fixes:
- DeleteFile.js: use path.resolve() + symlink protection (CRITICAL)
- DeleteFileFolder.js: add path.resolve() validation + symlink check (CRITICAL)
- RenameFile.js: use path.resolve() with proper prefix check + symlink guard (HIGH)
- attachments.js: add baseDir validation + skip symlinks in recursive search (MEDIUM)

XSS fixes:
- dashboard.js: escape user input in onerror/onclick inline attributes (HIGH)
- paramadminsettingsetup.script.js: escape values in innerHTML template (MEDIUM)

Input validation:
- inputValidationMiddleware.js: block suspicious requests instead of logging only (MEDIUM)

Version bump: 1.2.2-beta → 1.2.3-beta
2026-03-12 20:18:28 +01:00
1fbfc28780 Merge pull request 'security: vulnerability fixes & security hardening (2026-03-12)' (#1) from secops/security-update-2026-03-12 into release-candidate
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone Build is passing
Reviewed-on: #1
2026-03-12 17:27:34 +01:00
76dc23c861 security: fix vulnerabilities and update security hardening (2026-03-12)
Code security fixes:
- Fixed 3 critical auth bypass bugs (user.jso, typo → user.json) in RenameFile, NewFolder, DeleteFolder API routes
- Added URL validation (HTTP/HTTPS only) on ProfilPicture and BackgroundCustom endpoints to prevent stored XSS/CSS injection
- Added path traversal protection in Upload.js (resolved path boundary check)
- Removed unsafe-eval from CSP script-src directive
- Removed information disclosure in BuildMetaData error responses
- Removed unused child_process import in BuildMetaData.js

Version bump: 1.2.1-beta → 1.2.2-beta
2026-03-12 17:16:16 +01:00
15 changed files with 135 additions and 42 deletions

View File

@@ -171,7 +171,8 @@ const inputValidationMiddleware = (req, res, next) => {
if (req.body && typeof req.body === 'object') { if (req.body && typeof req.body === 'object') {
const bodyStr = JSON.stringify(req.body); const bodyStr = JSON.stringify(req.body);
if (suspiciousPatterns.some(pattern => pattern.test(bodyStr))) { if (suspiciousPatterns.some(pattern => pattern.test(bodyStr))) {
logger.warn(`Suspicious input detected in request body from ${req.ip}: ${req.path}`); logger.warn(`Suspicious input blocked in request body from ${req.ip}: ${req.path}`);
return res.status(400).json({ error: 'Input invalide détecté.' });
} }
} }
@@ -179,11 +180,11 @@ const inputValidationMiddleware = (req, res, next) => {
if (req.query && typeof req.query === 'object') { if (req.query && typeof req.query === 'object') {
const queryStr = JSON.stringify(req.query); const queryStr = JSON.stringify(req.query);
if (suspiciousPatterns.some(pattern => pattern.test(queryStr))) { if (suspiciousPatterns.some(pattern => pattern.test(queryStr))) {
logger.warn(`Suspicious input detected in query params from ${req.ip}: ${req.path}`); logger.warn(`Suspicious input blocked in query params from ${req.ip}: ${req.path}`);
return res.status(400).json({ error: 'Input invalide détecté.' });
} }
} }
// Continuer sans bloquer (logging only pour ne pas casser l'app)
next(); next();
} catch (error) { } catch (error) {
logger.error('Error in input validation middleware:', error); logger.error('Error in input validation middleware:', error);

View File

@@ -12,7 +12,7 @@ const securityHeadersMiddleware = (req, res, next) => {
'Content-Security-Policy', 'Content-Security-Policy',
[ [
"default-src 'self'", "default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://cdn.jsdelivr.net https://cdn.tailwindcss.com", "script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://cdn.jsdelivr.net https://cdn.tailwindcss.com",
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com", "style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com",
"img-src 'self' data: https: blob:", "img-src 'self' data: https: blob:",
"font-src 'self' https://cdnjs.cloudflare.com https://fonts.gstatic.com", "font-src 'self' https://cdnjs.cloudflare.com https://fonts.gstatic.com",

View File

@@ -1,6 +1,6 @@
{ {
"name": "@cdn-app/insider-myaxrin-labs-dinawo", "name": "@cdn-app/insider-myaxrin-labs-dinawo",
"version": "1.2.1-beta", "version": "1.2.3-beta",
"description": "", "description": "",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {

View File

@@ -1,4 +1,10 @@
// Dashboard JavaScript - Version corrigée // Dashboard JavaScript - Version corrigée
function escapeAttr(str) {
if (typeof str !== 'string') return '';
return str.replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Initialisation générale // Initialisation générale
initializeDashboard(); initializeDashboard();
@@ -683,9 +689,9 @@ function createCollaborationModal(itemName, itemType, data) {
<div class="collaboration-user-item"> <div class="collaboration-user-item">
<div class="user-avatar-wrapper"> <div class="user-avatar-wrapper">
<img src="${user.profilePicture || getDefaultAvatar(user.name)}" <img src="${user.profilePicture || getDefaultAvatar(user.name)}"
alt="${user.name}" alt="${escapeAttr(user.name)}"
class="user-avatar" class="user-avatar"
onerror="this.src='${getDefaultAvatar(user.name)}'"> onerror="this.src='${escapeAttr(getDefaultAvatar(user.name))}'">
<div class="user-status-indicator"></div> <div class="user-status-indicator"></div>
</div> </div>
<div class="user-details"> <div class="user-details">
@@ -697,7 +703,7 @@ function createCollaborationModal(itemName, itemType, data) {
</div> </div>
<div class="user-actions"> <div class="user-actions">
<button class="action-btn remove-btn" <button class="action-btn remove-btn"
onclick="removeCollaborator('${itemName}', '${itemType}', '${user.id}')" onclick="removeCollaborator('${escapeAttr(itemName)}', '${escapeAttr(itemType)}', '${escapeAttr(user.id)}')"
title="Retirer ce collaborateur"> title="Retirer ce collaborateur">
<i class="fas fa-user-minus"></i> <i class="fas fa-user-minus"></i>
</button> </button>
@@ -795,9 +801,9 @@ function searchCollabUser(username, itemName, itemType, modal) {
<div class="result-user-info"> <div class="result-user-info">
<div class="result-avatar-wrapper"> <div class="result-avatar-wrapper">
<img src="${result.user.profilePicture || getDefaultAvatar(result.user.name)}" <img src="${result.user.profilePicture || getDefaultAvatar(result.user.name)}"
alt="${result.user.name}" alt="${escapeAttr(result.user.name)}"
class="result-avatar" class="result-avatar"
onerror="this.src='${getDefaultAvatar(result.user.name)}'"> onerror="this.src='${escapeAttr(getDefaultAvatar(result.user.name))}'">
</div> </div>
<div class="result-details"> <div class="result-details">
<div class="result-name">${result.user.name}</div> <div class="result-name">${result.user.name}</div>
@@ -808,7 +814,7 @@ function searchCollabUser(username, itemName, itemType, modal) {
</div> </div>
</div> </div>
<button class="btn btn-primary add-user-btn" <button class="btn btn-primary add-user-btn"
onclick="addCollaborator('${itemName}', '${itemType}', '${result.user.id}')" onclick="addCollaborator('${escapeAttr(itemName)}', '${escapeAttr(itemType)}', '${escapeAttr(result.user.id)}')"
title="Ajouter ce collaborateur"> title="Ajouter ce collaborateur">
<i class="fas fa-user-plus"></i> <i class="fas fa-user-plus"></i>
<span>Ajouter</span> <span>Ajouter</span>

View File

@@ -1,3 +1,8 @@
function escapeAttr(str) {
if (typeof str !== 'string') return '';
return str.replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
const body = document.body; const body = document.body;
const themeSwitcher = document.getElementById('themeSwitcher'); const themeSwitcher = document.getElementById('themeSwitcher');
@@ -319,11 +324,11 @@ function addPath(type) {
const div = document.createElement('div'); const div = document.createElement('div');
div.className = 'flex items-center space-x-2 py-2 px-3 bg-gray-800 rounded-lg animate'; div.className = 'flex items-center space-x-2 py-2 px-3 bg-gray-800 rounded-lg animate';
div.innerHTML = ` div.innerHTML = `
<span class="flex-1">${value}</span> <span class="flex-1">${escapeAttr(value)}</span>
<button type="button" onclick="removePath(this)" class="text-gray-400 hover:text-red-500"> <button type="button" onclick="removePath(this)" class="text-gray-400 hover:text-red-500">
<i class="fas fa-times"></i> <i class="fas fa-times"></i>
</button> </button>
<input type="hidden" name="logs[${type === 'exclude' ? 'excludePaths' : 'includeOnly'}][]" value="${value}"> <input type="hidden" name="logs[${type === 'exclude' ? 'excludePaths' : 'includeOnly'}][]" value="${escapeAttr(value)}">
`; `;
list.appendChild(div); list.appendChild(div);
input.value = ''; input.value = '';

View File

@@ -1,7 +1,6 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const os = require('os'); const os = require('os');
const child_process = require('child_process');
const packageJson = require('../package.json'); const packageJson = require('../package.json');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@@ -64,7 +63,7 @@ router.get('/', async (req, res) => {
res.json(buildMetadata); res.json(buildMetadata);
} catch (error) { } catch (error) {
console.error('Error in /build-metadata: ', error); console.error('Error in /build-metadata: ', error);
res.status(500).send('Error in /build-metadata: ' + error.toString()); res.status(500).send('Internal server error');
} }
}); });

View File

@@ -13,6 +13,16 @@ router.post('/wallpaper', (req, res) => {
return res.status(400).send('No wallpaper URL provided.'); return res.status(400).send('No wallpaper URL provided.');
} }
// Validate URL to prevent XSS/CSS injection via malicious URLs
try {
const parsed = new URL(wallpaperUrl);
if (!['http:', 'https:'].includes(parsed.protocol)) {
return res.status(400).send('Invalid URL protocol. Only HTTP/HTTPS allowed.');
}
} catch {
return res.status(400).send('Invalid URL format.');
}
updateUserWallpaper(userId, wallpaperUrl, res); updateUserWallpaper(userId, wallpaperUrl, res);
}); });

View File

@@ -156,19 +156,30 @@ router.post('/', authenticateToken, (req, res) => {
return res.status(400).json({ message: 'User ID or filename missing for file deletion.' }); return res.status(400).json({ message: 'User ID or filename missing for file deletion.' });
} }
const userFolderPath = path.join('cdn-files', userId); const userFolderPath = path.resolve('cdn-files', userId);
function findAndDeleteFile(folderPath) { function findAndDeleteFile(folderPath) {
const resolvedFolder = path.resolve(folderPath);
if (!resolvedFolder.startsWith(userFolderPath + path.sep) && resolvedFolder !== userFolderPath) {
return false;
}
const filesInFolder = fs.readdirSync(folderPath); const filesInFolder = fs.readdirSync(folderPath);
for (const file of filesInFolder) { for (const file of filesInFolder) {
const filePath = path.join(folderPath, file); const filePath = path.join(folderPath, file);
const resolvedFilePath = path.resolve(filePath);
if (!filePath.startsWith(userFolderPath)) { if (!resolvedFilePath.startsWith(userFolderPath + path.sep)) {
return false; return false;
} }
if (fs.statSync(filePath).isDirectory()) { const stat = fs.lstatSync(filePath);
if (stat.isSymbolicLink()) {
continue;
}
if (stat.isDirectory()) {
const fileDeletedInSubfolder = findAndDeleteFile(filePath); const fileDeletedInSubfolder = findAndDeleteFile(filePath);
if (fileDeletedInSubfolder) { if (fileDeletedInSubfolder) {
return true; return true;

View File

@@ -26,8 +26,25 @@ router.post('/:folderName', authMiddleware, (req, res) => {
const userId = req.userData.name; const userId = req.userData.name;
const { filename } = req.body; const { filename } = req.body;
const userFolderPath = path.join('cdn-files', userId || ''); if (!userId || !filename) {
const filePath = path.join(userFolderPath, req.params.folderName, filename || ''); return res.status(400).json({ error: 'Paramètres manquants.' });
}
const userFolderPath = path.resolve('cdn-files', userId);
const filePath = path.resolve(userFolderPath, req.params.folderName, filename);
if (!filePath.startsWith(userFolderPath + path.sep)) {
return res.status(403).json({ error: 'Accès non autorisé.' });
}
try {
const stat = fs.lstatSync(filePath);
if (stat.isSymbolicLink()) {
return res.status(403).json({ error: 'Accès non autorisé.' });
}
} catch (e) {
return res.status(404).json({ error: 'Le fichier spécifié n\'existe pas.' });
}
if (!fs.existsSync(filePath)) { if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Le fichier spécifié n\'existe pas.' }); return res.status(404).json({ error: 'Le fichier spécifié n\'existe pas.' });

View File

@@ -129,9 +129,9 @@ function authenticateToken(req, res, next) {
return res.status(401).json({ message: 'Unauthorized' }); return res.status(401).json({ message: 'Unauthorized' });
} }
fs.readFile(path.join(__dirname, '../../../data', 'user.jso,'), 'utf8', (err, data) => { fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) { if (err) {
console.error('Error reading user.jso,:', err); console.error('Error reading user.json:', err);
return res.status(401).json({ message: 'Unauthorized' }); return res.status(401).json({ message: 'Unauthorized' });
} }

View File

@@ -105,7 +105,7 @@ function authenticateToken(req, res, next) {
return res.status(401).json({ message: 'Unauthorized' }); return res.status(401).json({ message: 'Unauthorized' });
} }
fs.readFile(path.join(__dirname, '../../../data', 'user.jso,'), 'utf8', (err, data) => { fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) { if (err) {
console.error('Error reading user.json:', err); console.error('Error reading user.json:', err);
return res.status(401).json({ message: 'Unauthorized' }); return res.status(401).json({ message: 'Unauthorized' });

View File

@@ -13,6 +13,16 @@ router.post('/', (req, res) => {
return res.status(400).send('No profile picture URL provided.'); return res.status(400).send('No profile picture URL provided.');
} }
// Validate URL to prevent XSS/injection via malicious URLs
try {
const parsed = new URL(profilePictureUrl);
if (!['http:', 'https:'].includes(parsed.protocol)) {
return res.status(400).send('Invalid URL protocol. Only HTTP/HTTPS allowed.');
}
} catch {
return res.status(400).send('Invalid URL format.');
}
updateUserProfilePicture(userId, profilePictureUrl, res); updateUserProfilePicture(userId, profilePictureUrl, res);
}); });

View File

@@ -107,7 +107,7 @@ function authenticateToken(req, res, next) {
} }
} }
fs.readFile(path.join(__dirname, '../../../data', 'user.jso,'), 'utf8', (err, data) => { fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) { if (err) {
console.error('Error reading user.json:', err); console.error('Error reading user.json:', err);
return res.status(401).json({ message: 'Unauthorized' }); return res.status(401).json({ message: 'Unauthorized' });
@@ -142,16 +142,21 @@ router.post('/', authMiddleware, async (req, res) => {
return res.status(400).json('Both currentName and newName must be provided.'); return res.status(400).json('Both currentName and newName must be provided.');
} }
const userDir = path.join('cdn-files', userId); const userDir = path.resolve('cdn-files', userId);
const currentPath = path.join(userDir, filePath, currentName); const currentPath = path.resolve(userDir, filePath, currentName);
const newPath = path.join(userDir, filePath, newName); const newPath = path.resolve(userDir, filePath, newName);
if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) { if (!currentPath.startsWith(userDir + path.sep) || !newPath.startsWith(userDir + path.sep)) {
ErrorLogger.error('Unauthorized directory access attempt'); ErrorLogger.error('Unauthorized directory access attempt');
return res.status(403).json('Unauthorized directory access attempt'); return res.status(403).json('Unauthorized directory access attempt');
} }
try { try {
const stat = await fs.promises.lstat(currentPath);
if (stat.isSymbolicLink()) {
return res.status(403).json('Unauthorized: symbolic links are not allowed');
}
await fs.promises.rename(currentPath, newPath); await fs.promises.rename(currentPath, newPath);
const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8'); const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8');
@@ -186,16 +191,21 @@ router.post('/:filePath*', authMiddleware, async (req, res) => {
return res.status(400).json('Both currentName and newName must be provided.'); return res.status(400).json('Both currentName and newName must be provided.');
} }
const userDir = path.join('cdn-files', userId); const userDir = path.resolve('cdn-files', userId);
const currentPath = path.join(userDir, filePath, currentName); const currentPath = path.resolve(userDir, filePath, currentName);
const newPath = path.join(userDir, filePath, newName); const newPath = path.resolve(userDir, filePath, newName);
if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) { if (!currentPath.startsWith(userDir + path.sep) || !newPath.startsWith(userDir + path.sep)) {
ErrorLogger.error('Unauthorized directory access attempt'); ErrorLogger.error('Unauthorized directory access attempt');
return res.status(403).json('Unauthorized directory access attempt'); return res.status(403).json('Unauthorized directory access attempt');
} }
try { try {
const stat = await fs.promises.lstat(currentPath);
if (stat.isSymbolicLink()) {
return res.status(403).json('Unauthorized: symbolic links are not allowed');
}
await fs.promises.rename(currentPath, newPath); await fs.promises.rename(currentPath, newPath);
const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8'); const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8');

View File

@@ -68,6 +68,14 @@ router.post('/', (req, res) => {
const filename = fields.filename ? fields.filename[0] : file.originalFilename; const filename = fields.filename ? fields.filename[0] : file.originalFilename;
const filePath = path.join(userDir, filename); const filePath = path.join(userDir, filename);
// Path traversal protection: ensure resolved path stays within user directory
const resolvedUserDir = path.resolve(process.cwd(), 'cdn-files', userName);
const resolvedFilePath = path.resolve(filePath);
if (!resolvedFilePath.startsWith(resolvedUserDir + path.sep) && resolvedFilePath !== resolvedUserDir) {
if (fs.existsSync(file.path)) fs.unlinkSync(file.path);
return res.status(403).send('Path traversal detected');
}
// Récupérer les champs supplémentaires // Récupérer les champs supplémentaires
const expiryDate = fields.expiryDate ? fields.expiryDate[0] : ''; const expiryDate = fields.expiryDate ? fields.expiryDate[0] : '';
const password = fields.password ? fields.password[0] : ''; const password = fields.password ? fields.password[0] : '';

View File

@@ -30,21 +30,37 @@ async function findFileInUserDir(userId, filename) {
return findFileInDir(userDir, filename); return findFileInDir(userDir, filename);
} }
async function findFileInDir(dir, filename) { async function findFileInDir(dir, filename, baseDir) {
if (!baseDir) baseDir = dir;
const resolvedDir = path.resolve(dir);
const resolvedBase = path.resolve(baseDir);
if (resolvedDir !== resolvedBase && !resolvedDir.startsWith(resolvedBase + path.sep)) {
return null;
}
let files; let files;
try { try {
files = await fs.readdir(dir, { withFileTypes: true }); files = await fs.readdir(dir, { withFileTypes: true });
} catch (err) { } catch (err) {
return null; // Directory does not exist return null;
} }
for (const file of files) { for (const file of files) {
const filePath = path.join(dir, file.name); const filePath = path.join(dir, file.name);
if (file.isSymbolicLink()) {
continue;
}
if (file.name === filename && file.isFile()) { if (file.name === filename && file.isFile()) {
const resolvedFile = path.resolve(filePath);
if (resolvedFile.startsWith(resolvedBase + path.sep)) {
return filePath; return filePath;
}
return null;
} else if (file.isDirectory()) { } else if (file.isDirectory()) {
const found = await findFileInDir(filePath, filename); const found = await findFileInDir(filePath, filename, baseDir);
if (found) { if (found) {
return found; return found;
} }