Files
wekan/server/lib/filenameSanitizeLog.js
T
Lauri Ojansivu d577f07700 Canary tokens: who tried to override permissions, and from where.
The security event log said what a guard DID - a request blocked, a filename
sanitized - which answers "is WeKan defending itself" and not the question an
admin asks next: who did that, and from where. It also could not tell a browser
that got confused from somebody working through the Hall of Fame one entry at a
time.

A CANARY is a tripwire at a point that only a permission-override attempt
reaches. Ordinary use never gets there - the code path runs when a request asks
for something the rules forbid - so a trip is not noise, and it is worth an
admin's attention with the actor attached. Design:
docs/Security/Remediation/WeKan.md §12.

Three properties, each enforced by a test:

SILENT. Tripping one changes NOTHING the caller can observe. tripCanary()
always returns false and tripCanaryDeny() always returns true, so a call site
reads as the refusal it replaces:

    if (forbidden) return false;                          // before
    if (forbidden) return tripCanary('card.vote-field', { userId });

The return value is decided before any reporting is attempted and the reporting
is wrapped, so a canary can never throw into, delay or disturb the request it
watches. The REST handler re-throws the ORIGINAL error object. This is not
politeness: a canary that announces itself is a map of which paths are watched,
and a probe would simply avoid them.

BOUNDED. A canary sits where an attacker can loop, so one row per attempt would
be a denial of service they get for free. models/lib/canaryTokens.js - pure, no
Meteor, no clock of its own - records the first trip of a (canary, actor) pair
at once, COUNTS the rest of the window, flushes one summary carrying the total
when the window closes, and stops writing after 60 summaries for a pair that
never gives up. The tracked-pair map is capped at 5000 and evicts the LEAST
RECENTLY seen, so a long-running attacker is not pushed out by a passing one and
a botnet varying its address cannot grow it. Idle pairs are swept on a timer. A
thousand attempts in a minute cost ONE row, and a suppressed trip costs one map
lookup. The username lookup is cached and capped, and neither it nor the insert
is awaited on the caller's path.

ATTRIBUTED. Every event carries userId, username, ip and count. The username is
denormalised at write time on purpose: it is what the account was CALLED when it
tried, so a rename does not rewrite history and a deletion does not erase it.
The address uses the same spoofing-safe resolver as the login throttle -
X-Forwarded-For only as far as HTTP_FORWARDED_COUNT says to trust it - or an
attacker could write a colleague's address into the security log by sending a
header. `detail` says what was attempted in the words of the feature, never the
payload.

Seventeen canaries are wired at the permission checks that refuse the attempts
behind BoardBleed, ParentBleed, ChecklistBleed, PathBleed and CommentBleed, plus
the direct vote/poker field writes and a stored path that points outside the
storage root. All server-side: no Playwright, no browser, nothing to install.

Admin Panel / Problems / Security gains Username, IP address and Attempts
columns, and both new columns are searchable - the thing an admin does with one
security event is pivot on it.

tests/canaryTokens.test.cjs (25 checks) drives the limiter through bursts, an
endless probe, eviction order and junk input; tests/canaryCoverage.test.cjs (18)
pins every canary to its call site and asserts none of them changes what the
caller gets back.

Thanks to xet7 !
2026-08-09 03:29:20 +03:00

85 lines
4.0 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.
'use strict';
// Log filename / file-content SANITIZATION events (not just blocks) to the Admin
// Panel → Problems → Security stream, so an admin can see EVERY time a filename or
// file required sanitization, FOR WHAT REASON (which exploit kind, wrong file type,
// typosquatting, too long, …), WHO originally uploaded it, WHEN, and WHERE it was
// uploaded (board › swimlane › list › card, organization and team).
//
// These are the `action:'sanitized'` companions to the `action:'blocked'` events
// already recorded by models/fileValidation.js. The uploader is stored as `userId`
// (shown, clickable, in the report) and the full context is appended to `detail`.
// Best-effort and server-only: never throws into the upload/migration/view path.
const { resolveFileContext, formatFileContext } = require('/server/lib/fileContext');
function record(evt) {
try {
require('/server/lib/securityLog').record(evt);
} catch (e) { /* logging must never break the caller */ }
}
// Sanitizing a filename is routine - names get trimmed, unicode gets normalised,
// an extension gets corrected - and routine is not worth an admin's attention.
// What IS worth it is a name that carried an EXPLOIT: markup, a shell
// metacharacter, a path trying to leave its directory. Those reasons, and only
// those, also trip a canary, so the Security report separates "somebody uploaded
// a file with an awkward name" from "somebody is probing the upload path"
// (docs/Security/Remediation/WeKan.md §12.6).
const DANGEROUS_REASON = /^exploit: |traversal|invisible characters|URL-encoded name/i;
function canaryForReasons(reasons, fileObj) {
try {
const list = Array.isArray(reasons) ? reasons : [];
const dangerous = list.filter(r => typeof r === 'string' && DANGEROUS_REASON.test(r));
if (!dangerous.length) return;
const traversal = dangerous.some(r => /traversal/i.test(r));
const { tripCanary } = require('/server/lib/canary');
tripCanary(traversal ? 'sanitize.path-traversal' : 'sanitize.dangerous-filename', {
userId: (fileObj && (fileObj.userId || (fileObj.meta && fileObj.meta.userId))) || undefined,
// The REASONS, which are a short fixed vocabulary - never the filename,
// which is the attacker's own text.
detail: dangerous.slice(0, 4).join(', '),
});
} catch (e) { /* a canary must never break an upload */ }
}
// Record that a stored filename was sanitized. `reasons` is the array from
// uploadFileName.sanitizationReasons(); `fileObj` supplies the uploader + location.
async function logFilenameSanitized({ fileObj, source, reasons, from, to }) {
try {
canaryForReasons(reasons, fileObj);
const why = Array.isArray(reasons) && reasons.length ? reasons.join('; ') : 'normalized';
let context = '';
try { context = formatFileContext(await resolveFileContext(fileObj)); } catch (e) { /* omit */ }
record({
key: 'file.sanitize',
action: 'sanitized',
source: source || 'fileUpload',
userId: (fileObj && fileObj.userId) || undefined,
detail: `${why}: "${from}" → "${to}"${context ? ' | ' + context : ''}`,
});
} catch (e) { /* never throw */ }
}
// Record that exploits were removed from a file's CONTENT (e.g. JavaScript / XML
// loop stripped from an SVG). `kinds` is the array from classifyExploitKinds().
async function logContentSanitized({ fileObj, source, kinds }) {
try {
const what = Array.isArray(kinds) && kinds.length ? kinds.join(', ') : 'active content (JavaScript / XML)';
const name = (fileObj && fileObj.name) || '';
let context = '';
try { context = formatFileContext(await resolveFileContext(fileObj)); } catch (e) { /* omit */ }
record({
key: 'file.content',
action: 'sanitized',
source: source || 'fileUpload',
userId: (fileObj && fileObj.userId) || undefined,
detail: `removed ${what} from file content "${name}"${context ? ' | ' + context : ''}`,
});
} catch (e) { /* never throw */ }
}
module.exports = { logFilenameSanitized, logContentSanitized };