mirror of
https://github.com/wekan/wekan.git
synced 2026-11-25 04:49:41 -05:00
The upload path-traversal guard was logging under the pre-existing PathBleed key (a different, already-published advisory, GHSA-4mxf-m8pq-xc9p about avatar versions.path and board export) - it now has its own UploadPathBleed key, so the two incidents are not conflated on the public Hall of Fame page or in Admin Panel / Problems. The two High advisories (missing Avatars.protected, unauthenticated serveLegacyAvatar) now also log a blocked attempt, under new authz.avatar-protected/PortraitBleed and authz.legacy-avatar/RelicAvatarBleed keys, matching the site entries added at .tools/wekan.fi. tests/securityRegressionCoverage.test.cjs's inventory and tests/attachmentAvatarSecurityAdvisories.test.cjs are updated so all four names (WipeBleed, UploadPathBleed, PortraitBleed, RelicAvatarBleed) are recognized as GUARDED, matching the published Hall of Fame count.
256 lines
10 KiB
JavaScript
256 lines
10 KiB
JavaScript
import { Meteor } from 'meteor/meteor';
|
|
import { Random } from 'meteor/random';
|
|
import { FilesCollection } from 'meteor/ostrio:files';
|
|
import { generateUniversalAttachmentUrl } from '/models/lib/universalUrlGenerator';
|
|
const { cleanFileName } = require('/imports/lib/fileNameDisplay');
|
|
|
|
// Pure helper: build the activity document for a newly added attachment.
|
|
// Kept side-effect free so it can be unit tested without a database.
|
|
// Mirrors the shape used for the 'deleteAttachment' activity, so card
|
|
// history rendering and member/subscriber notifications behave identically.
|
|
// see #5905
|
|
export function buildAttachmentAddedActivity(fileObj) {
|
|
const meta = (fileObj && fileObj.meta) || {};
|
|
return {
|
|
userId: fileObj && fileObj.userId,
|
|
type: 'card',
|
|
activityType: 'addAttachment',
|
|
attachmentId: fileObj && fileObj._id,
|
|
// preserve the name so notifications stay meaningful even after removal
|
|
attachmentName: fileObj && fileObj.name,
|
|
boardId: meta.boardId,
|
|
cardId: meta.cardId,
|
|
listId: meta.listId,
|
|
swimlaneId: meta.swimlaneId,
|
|
};
|
|
}
|
|
|
|
// XXX Enforce a schema for the Attachments FilesCollection
|
|
// see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema
|
|
|
|
// Compute storage path:
|
|
// - Docker (WRITABLE_PATH=/data): /data/files/attachments
|
|
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/attachments
|
|
const computeAttachmentStoragePath = () => {
|
|
const basePath = process.env.WRITABLE_PATH || process.cwd();
|
|
const endsWithFiles = basePath.endsWith('/files') || basePath.endsWith('\\files');
|
|
if (endsWithFiles) {
|
|
// Snap: WRITABLE_PATH already includes /files
|
|
return basePath + '/attachments';
|
|
} else {
|
|
// Docker & Dev: append /files/attachments
|
|
return basePath + '/files/attachments';
|
|
}
|
|
};
|
|
|
|
const storagePath = Meteor.isServer ? computeAttachmentStoragePath() : 'assets/app/uploads/attachments';
|
|
|
|
const Attachments = new FilesCollection({
|
|
debug: false,
|
|
collectionName: 'attachments',
|
|
allowClientCode: true,
|
|
storagePath: storagePath,
|
|
namingFunction(opts) {
|
|
let filenameWithoutExtension = ""
|
|
let fileId = "";
|
|
if (opts?.name) {
|
|
// Client
|
|
filenameWithoutExtension = opts.name.replace(/(.+)\..+/, "$1");
|
|
fileId = opts.meta.fileId;
|
|
delete opts.meta.fileId;
|
|
} else if (opts?.file?.name) {
|
|
// Server
|
|
if (opts.file.extension) {
|
|
filenameWithoutExtension = opts.file.name.replace(new RegExp(opts.file.extensionWithDot + "$"), "")
|
|
} else {
|
|
// file has no extension, so don't replace anything, otherwise the last character is removed (because extensionWithDot = '.')
|
|
filenameWithoutExtension = opts.file.name;
|
|
}
|
|
fileId = opts.fileId;
|
|
}
|
|
else {
|
|
// should never reach here
|
|
filenameWithoutExtension = Math.random().toString(36).slice(2);
|
|
fileId = Math.random().toString(36).slice(2);
|
|
}
|
|
|
|
// OLD:
|
|
//const ret = fileId + "-original-" + filenameWithoutExtension;
|
|
// NEW: Save file only with filename of ObjectID, not including filename.
|
|
// Fixes https://github.com/wekan/wekan/issues/4416#issuecomment-1510517168
|
|
//
|
|
// SECURITY (path traversal / arbitrary file write): fileId is
|
|
// client-supplied (opts.fileId on the server branch, opts.meta.fileId on
|
|
// the client one) and is used VERBATIM as the on-disk file name below -
|
|
// this.sanitize() just above in the upload pipeline already strips
|
|
// path-traversal/shell characters (see the comment on sanitize() below),
|
|
// but require the result to also look like the ObjectId WeKan itself
|
|
// generates, so a malformed or unexpected value can never reach the
|
|
// filesystem at all rather than merely losing its dangerous characters.
|
|
if (!fileId || !/^[a-zA-Z0-9_-]{1,40}$/.test(fileId)) {
|
|
if (Meteor.isServer) {
|
|
// An attempt: no legitimate WeKan client ever sends a fileId that
|
|
// fails this check, so this line is what an anonymous namingFunction
|
|
// exploit attempt against Advisory "Unauthenticated Arbitrary File
|
|
// Write via Path Traversal in Attachment Upload namingFunction"
|
|
// looks like server-side.
|
|
try {
|
|
require('/server/lib/securityLog').record({
|
|
key: 'authz.upload-path',
|
|
action: 'blocked',
|
|
source: 'Attachments.namingFunction',
|
|
detail: 'rejected a malformed/unsafe fileId, generated a fresh one instead',
|
|
});
|
|
} catch (e) { /* logging must never break the upload */ }
|
|
}
|
|
fileId = Random.id();
|
|
}
|
|
const ret = fileId;
|
|
// remove fileId from meta, it was only stored there to have this information here in the namingFunction function
|
|
return ret;
|
|
},
|
|
sanitize(str, max, replacement) {
|
|
// SECURITY (path traversal / arbitrary file write): this used to be an
|
|
// identity function ("keep the original filename"), but ostrio:files
|
|
// never calls this.sanitize() on the human-readable file name - only on
|
|
// fileId/FSName, the tokens it uses to build the ON-DISK PATH before any
|
|
// containment check (server.js's DDP _Start/_Write methods and the HTTP
|
|
// __upload route all call `this.sanitize(opts.fileId, 20, 'a')` first).
|
|
// An identity sanitize let a client-supplied fileId like
|
|
// "../../../../tmp/pwn" flow straight through to the physical path.
|
|
// Restored to the same whitelist models/avatars.js already uses for the
|
|
// same tokens - file DISPLAY names are untouched, they are sanitized
|
|
// separately in onBeforeUpload below.
|
|
return (str || '').replace(/[^a-zA-Z0-9_.\-]/g, replacement || '_');
|
|
},
|
|
onBeforeUpload(file) {
|
|
// SECURITY: Sanitize filename to prevent path traversal attacks
|
|
if (file.name && typeof file.name === 'string') {
|
|
// Strip directory components (client-safe alternative to path.basename)
|
|
let safeName = file.name.split(/[\\/]/).pop();
|
|
// Remove null bytes
|
|
safeName = safeName.replace(/\0/g, '');
|
|
// Remove path traversal sequences (repeat until stable to avoid incomplete multi-character sanitization)
|
|
let previousSafeName;
|
|
do {
|
|
previousSafeName = safeName;
|
|
safeName = safeName.replace(/\.\.[\\/]/g, '');
|
|
} while (safeName !== previousSafeName);
|
|
safeName = safeName.replace(/^\.\.$/g, '');
|
|
safeName = safeName.trim();
|
|
|
|
// If sanitization changed the name, update it
|
|
if (safeName && safeName !== '.' && safeName !== '..' && safeName !== file.name) {
|
|
file.name = safeName;
|
|
} else if (!safeName || safeName === '.' || safeName === '..') {
|
|
file.name = 'unnamed';
|
|
}
|
|
// Apply the same plain-text and classic Amiga FFS 30-character policy
|
|
// before bytes leave the client. Content-derived extension correction is
|
|
// repeated authoritatively on the server after its bounded header sniff.
|
|
file.name = cleanFileName(file.name) || 'unnamed';
|
|
}
|
|
|
|
// Block SVG files for attachments to prevent XSS attacks
|
|
if (file.name && file.name.toLowerCase().endsWith('.svg')) {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Blocked SVG file upload for attachment:', file.name);
|
|
}
|
|
return 'SVG files are not allowed for attachments due to security reasons. Please use PNG, JPG, GIF, or other safe formats.';
|
|
}
|
|
|
|
if (file.type === 'image/svg+xml') {
|
|
if (process.env.DEBUG === 'true') {
|
|
console.warn('Blocked SVG MIME type upload for attachment:', file.type);
|
|
}
|
|
return 'SVG files are not allowed for attachments due to security reasons. Please use PNG, JPG, GIF, or other safe formats.';
|
|
}
|
|
|
|
return true;
|
|
},
|
|
});
|
|
|
|
function normalizeRemovedFiles(filesInput) {
|
|
if (!filesInput) {
|
|
return [];
|
|
}
|
|
|
|
if (Array.isArray(filesInput)) {
|
|
return filesInput;
|
|
}
|
|
|
|
if (typeof filesInput.fetch === 'function') {
|
|
return filesInput.fetch();
|
|
}
|
|
|
|
if (Array.isArray(filesInput.files)) {
|
|
return filesInput.files;
|
|
}
|
|
|
|
if (typeof filesInput === 'string') {
|
|
return Attachments.find({ _id: filesInput }).fetch();
|
|
}
|
|
|
|
if (filesInput && typeof filesInput === 'object') {
|
|
if (filesInput._id && (filesInput.versions || filesInput.meta)) {
|
|
return [filesInput];
|
|
}
|
|
|
|
return Attachments.find(filesInput).fetch();
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
// Export normalizeRemovedFiles for use in server file
|
|
export { normalizeRemovedFiles };
|
|
|
|
// Backward compatibility stubs (overridden in attachments.server.js with real implementations)
|
|
Attachments.getAttachmentWithBackwardCompatibility = async () => null;
|
|
Attachments.getAttachmentsWithBackwardCompatibility = async () => [];
|
|
|
|
// Override Attachments.link to use universal short URLs and to bypass
|
|
// the `check(fileRef, Object)` inside the original which fails when fileRef is
|
|
// a collection-helpers class instance (not a plain object).
|
|
// Uses short URL format handled by universalFileServer.js.
|
|
if (Meteor.isClient) {
|
|
Attachments.link = function () {
|
|
let fileRef;
|
|
if (this && this._id) {
|
|
// Called as instance method: doc.link(version)
|
|
fileRef = this;
|
|
} else if (arguments[0] && arguments[0]._id) {
|
|
// Called as static from FileCursor: Attachments.link(fileRef, version)
|
|
fileRef = arguments[0];
|
|
} else {
|
|
return '';
|
|
}
|
|
return generateUniversalAttachmentUrl(fileRef._id);
|
|
};
|
|
}
|
|
|
|
// #5905: Notify card members/subscribers and record card history when a new
|
|
// attachment is uploaded. The 'deleteAttachment' activity is already created
|
|
// (via the store strategy's onAfterRemove during file removal), but the matching
|
|
// 'addAttachment' activity was never created during the upload flow. Create it
|
|
// here with a server-side collection insert hook, mirroring the original
|
|
// behaviour. The generic Activities after.insert hook (server/models/activities.js)
|
|
// then notifies card members + watchers, deduplicated, exactly as it does for
|
|
// every other card activity.
|
|
if (Meteor.isServer) {
|
|
Attachments.collection.after.insert((userId, doc) => {
|
|
// Skip attachments created during a board/card import: those are not
|
|
// user-driven uploads and should not generate notifications.
|
|
if (doc.meta && doc.meta.source === 'import') {
|
|
return;
|
|
}
|
|
// Lazy import to keep this out of the client bundle.
|
|
const Activities = require('/models/activities').default;
|
|
Activities.insertAsync(buildAttachmentAddedActivity(doc)).catch(error => {
|
|
console.error('Failed to insert addAttachment activity:', error);
|
|
});
|
|
});
|
|
}
|
|
|
|
export default Attachments;
|