Files
wekan/models/fileValidation.js
T
Lauri Ojansivu 1a222c4477 - **[ScannerBleed](https://github.com/wekan/wekan/security/advisories/GHSA-x3xm-pxrv-jg7p)
— shell injection (RCE) via a malicious upload filename in the external antivirus scanner command path**
  ([GHSA-x3xm-pxrv-jg7p](https://github.com/wekan/wekan/security/advisories/GHSA-x3xm-pxrv-jg7p),
  CWE-78 OS Command Injection). Same RCE class as
  [AvatarBleed](https://wekan.fi/hall-of-fame/avatarbleed/) (CVE-2026-52891, GHSA-35j7-h385-2q9g)
  and its follow-up regression (CVE-2026-53447 / GHSA-qfqv-42qw-vvwh area), but in a code path that
  was **never** covered by those fixes.
  In `models/fileValidation.js`, when an admin has configured an external scanner (antivirus)
  command line with a `{file}` placeholder, the uploaded file path was interpolated into the command
  and run through `asyncExec` (`promisify(exec)`), which spawns `/bin/sh -c` and interprets **all**
  shell metacharacters:
  ```js
  await asyncExec(externalCommandLine.replace("{file}", '"' + fileObj.path + '"'));
  ```
  Wrapping the path in double quotes is not a shell boundary — inside double quotes the shell still
  expands `$(...)`, backticks and `\`, so a filename such as `` a`id`.png `` or `$(touch /tmp/pwn).png`
  escaped the argument and executed as the Wekan server process. Any **authenticated** user who can
  upload an attachment could trigger it, on servers that have an external scanner configured. Unlike
  the sibling MIME-detection path (`detectMimeFromFile`, which already uses `execFile` with no shell)
  and unlike the AvatarBleed fix (which strips non-alphanumeric characters from the filename), this
  scanner path had **zero** sanitization.
  - **Fixed** by POSIX single-quote-escaping the interpolated file path via a new `shellQuote()`
    helper (wrap in single quotes, escape embedded `'` as `'\''`). Inside single quotes the shell
    interprets no metacharacters, so a malicious filename can no longer break out of the argument or
    inject commands, while the admin's arbitrary command line and the exact on-disk path are both
    preserved. CVSS:3.1 9.9 Critical (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H).
  - Affected Wekan v9.06 and earlier through the current release; fixed at the upcoming WeKan release.
    Reported by **DavidCarliez**.

Thanks to DavidCarliez and xet7 !
2026-07-05 21:55:15 +03:00

172 lines
6.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Meteor } from 'meteor/meteor';
import { exec, execFile } from 'node:child_process';
import { promisify } from 'node:util';
import fs from 'fs';
let asyncExecFile;
let asyncExec;
if (Meteor.isServer) {
asyncExecFile = promisify(execFile);
// Shell-based exec, used only for the admin-configured external scanner
// command line below (which intentionally contains an arbitrary command and
// a {file} placeholder). MIME detection uses asyncExecFile to avoid any shell.
asyncExec = promisify(exec);
}
// POSIX-safe shell quoting for a single argument. Wraps the value in single
// quotes and escapes any embedded single quote as '\'' . Inside single quotes
// the shell interprets no metacharacters ($ ` \ ; | & > < * ? ( ) etc.), so the
// value cannot break out of the argument or inject additional commands. This is
// used for the file path interpolated into the admin-configured external scanner
// command line, which is executed through /bin/sh (CWE-78 shell injection).
function shellQuote(value) {
return "'" + String(value).replace(/'/g, "'\\''") + "'";
}
async function detectMimeFromFile(filePath) {
if (!Meteor.isServer) return undefined;
try {
// Use execFile instead of exec so no shell is spawned and the path is
// passed as a direct argument — this eliminates shell injection entirely.
const { stdout } = await asyncExecFile('file', ['--mime-type', '-b', String(filePath)]);
const mime = (stdout || '').trim().toLowerCase();
if (!mime) return undefined;
return { mime };
} catch (e) {
// Fall through to filename/type fallback handled by caller.
}
return undefined;
}
export async function isFileValid(fileObj, mimeTypesAllowed, sizeAllowed, externalCommandLine) {
let isValid = true;
// Always validate uploads. The previous migration flag disabled validation and enabled XSS.
try {
// Helper: read up to a limit from a file as UTF-8 text
const readTextHead = (filePath, limit = parseInt(process.env.UPLOAD_DANGEROUS_MIME_SCAN_LIMIT || '1048576')) => new Promise((resolve, reject) => {
try {
const stream = fs.createReadStream(filePath, { encoding: 'utf8', highWaterMark: 64 * 1024 });
let data = '';
let exceeded = false;
stream.on('data', chunk => {
data += chunk;
if (data.length >= limit) {
exceeded = true;
stream.destroy();
}
});
stream.on('error', err => reject(err));
stream.on('close', () => {
if (exceeded) {
// If file exceeds scan limit, treat as unsafe
resolve({ text: data.slice(0, limit), complete: false });
} else {
resolve({ text: data, complete: true });
}
});
} catch (e) {
reject(e);
}
});
// Helper: quick content safety checks for HTML/SVG/XML
const containsJsOrXmlBombs = (text) => {
if (!text) return false;
const t = text.toLowerCase();
// JavaScript execution vectors
const patterns = [
/<script\b/i,
/on[a-z\-]{1,20}\s*=\s*['"]/i, // event handlers
/javascript\s*:/i,
/<iframe\b/i,
/<object\b/i,
/<embed\b/i,
/<meta\s+http-equiv\s*=\s*['"]?refresh/i,
/<foreignobject\b/i,
/style\s*=\s*['"][^'"]*url\(\s*javascript\s*:/i,
];
if (patterns.some((re) => re.test(text))) return true;
// XML entity expansion / DTD based bombs
if (t.includes('<!doctype') || t.includes('<!entity') || t.includes('<?xml-stylesheet')) return true;
return false;
};
const checkDangerousMimeAllowance = async (mime, filePath, fileSize) => {
// Allow only if content is scanned and clean
const { text, complete } = await readTextHead(filePath);
if (!complete) {
// Too large to confidently scan
return false;
}
// For JS MIME, only allow empty files
if (mime === 'application/javascript' || mime === 'text/javascript') {
return (text.trim().length === 0);
}
return !containsJsOrXmlBombs(text);
};
// Detect MIME type from file content when possible
const mimeTypeResult = await detectMimeFromFile(fileObj.path);
const detectedMime = mimeTypeResult?.mime || (fileObj.type || '').toLowerCase();
const baseMimeType = detectedMime.split('/', 1)[0] || '';
// Hard deny-list for obviously dangerous types which can be allowed if content is safe
const dangerousMimes = new Set([
'text/html',
'application/xhtml+xml',
'image/svg+xml',
'text/xml',
'application/xml',
'application/javascript',
'text/javascript'
]);
if (dangerousMimes.has(detectedMime)) {
const allowedByContentScan = await checkDangerousMimeAllowance(detectedMime, fileObj.path, fileObj.size || 0);
if (!allowedByContentScan) {
console.log("Validation of uploaded file failed (dangerous MIME content): file " + fileObj.path + " - mimetype " + detectedMime);
return false;
}
}
// Optional allow-list: if provided, enforce it using exact or base type match
if (Array.isArray(mimeTypesAllowed) && mimeTypesAllowed.length) {
isValid = mimeTypesAllowed.includes(detectedMime)
|| (baseMimeType && mimeTypesAllowed.includes(baseMimeType + '/*'))
|| mimeTypesAllowed.includes('*');
if (!isValid) {
console.log("Validation of uploaded file failed: file " + fileObj.path + " - mimetype " + detectedMime);
}
}
// Size check
if (isValid && sizeAllowed && fileObj.size > sizeAllowed) {
console.log("Validation of uploaded file failed: file " + fileObj.path + " - size " + fileObj.size);
isValid = false;
}
// External scanner (e.g., antivirus) – expected to delete/quarantine bad files
if (isValid && externalCommandLine) {
// Shell-quote the file path so a malicious filename cannot inject shell
// commands into the admin-configured scanner command line (CWE-78 RCE).
await asyncExec(externalCommandLine.replace("{file}", shellQuote(fileObj.path)));
isValid = fs.existsSync(fileObj.path);
if (!isValid) {
console.log("Validation of uploaded file failed: file " + fileObj.path + " has been deleted externally");
}
}
if (isValid) {
console.debug("Validation of uploaded file successful: file " + fileObj.path);
}
} catch (e) {
console.error('Error during file validation:', e);
isValid = false;
}
return isValid;
}