Files
wekan/server/notifications/emailQueue.js
T
Lauri Ojansivu 3151f8a815 Fix ReplyBleed: attribute email replies to the recipient the address was sent to.
The reply-by-email token signed only the card, so every recipient of a
card's notification held the same Reply-To address, and the webhook took the
comment author from the reply's From address - a field the sender controls.
Anyone holding one card's reply address could comment on it as any user
(GHSA-mc7c-cv99-64h7, CWE-346).

Validation also found that server/routes/inboundEmail.js was never imported
by server/imports.js, so released versions did not register
/api/inbound-email: the documented feature did not work and the flaw could
not be reached. The endpoint is registered now, together with the fix.

The reply address is now reply+<cardId>.<userId>.<expiry>.<mac>: an
HMAC-SHA256 over the card, the recipient and the last valid day
(INBOUND_EMAIL_REPLY_DAYS, default 30). The author is that recipient; the
From address must be one of the recipient's own addresses; the recipient must
be enabled and still allowed to comment on the card, including the
assigned-only restriction. INBOUND_EMAIL_WEBHOOK_SECRET, when set, must be
presented by the provider (X-WeKan-Inbound-Secret header or ?secret=) and is
compared in constant time. The old card-only token is refused.

A forged token, a spoofed sender and a wrong provider secret are recorded as
ReplyBleed in Admin Panel -> Problems; expired and pre-fix tokens and lost
access are refused quietly, since real users replying to old mail reach them.

Tests: token round trip, per-recipient addresses, tampering, expiry and
legacy tokens; the author decision reproducing the advisory's attack; a
tree-wide negative that no code picks an author from a From address; and a
full-app HTTP test against /api/inbound-email.

Thanks to alex131125 and xet7 !
2026-09-30 10:52:45 +03:00

89 lines
5.0 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { ReactiveCache } from '/imports/reactiveCache';
import EmailLocalization from '/server/lib/emailLocalization';
import { resolveNotificationSetting } from '/models/lib/notificationSettings';
import { ensureIndex } from '/server/lib/mongoStartup';
const { createEmailOutbox, migrateLegacyEmailBuffer } = require('/server/lib/emailOutbox');
const { createEmailReceiptMaintenance, emailReceiptPolicy } = require('/server/lib/emailReceiptRetention');
const { createEmailSendSlots } = require('/server/lib/emailSendSlots');
const { buildReplyToAddress } = require('/server/lib/inboundEmailReplyToken');
// Mail payloads remain private; admin methods expose only recipient summaries.
export const EmailJobs = new Mongo.Collection('notificationEmailJobs');
export const EmailLeases = new Mongo.Collection('notificationEmailLeases');
export const EmailControls = new Mongo.Collection('notificationEmailControls');
export const EmailCommands = new Mongo.Collection('notificationEmailCommands');
export const EmailSendSlots = new Mongo.Collection('notificationEmailSendSlots');
for (const collection of [EmailJobs, EmailLeases, EmailControls, EmailCommands, EmailSendSlots]) {
collection.deny({ insert: () => true, update: () => true, remove: () => true });
}
const configuredDelay = Number(process.env.EMAIL_NOTIFICATION_TIMEOUT);
const delayMs = Number.isFinite(configuredDelay) && configuredDelay > 0 ? configuredDelay : 30000;
export const emailOutbox = createEmailOutbox({
withDeliverySlot: createEmailSendSlots(EmailSendSlots.rawCollection()),
jobs: EmailJobs.rawCollection(), controls: EmailControls.rawCollection(), leases: EmailLeases.rawCollection(), delayMs,
getUser: id => ReactiveCache.getUser(id),
send: mail => EmailLocalization.sendEmail(mail),
canReceive: async (user, job) => {
// Legacy profile buffers have no board identity to re-check. New jobs
// must still belong to an active member when the deferred send occurs.
const board = job.boardId ? await ReactiveCache.getBoard(job.boardId) : null;
if (job.boardId && !board?.members?.some(member => member.userId === user._id && member.isActive === true)) return false;
if (!job.boardId) return user.profile?.notifyOverrideEmail !== false;
const setting = await ReactiveCache.getCurrentSetting();
return resolveNotificationSetting('email', { adminDefault: setting?.notifyDefaultEmail,
boardOverride: board?.notifyOverrideEmail, memberOverride: user.profile?.notifyOverrideEmail });
},
from: () => Accounts.emailTemplates.from,
// ReplyBleed (GHSA-mc7c-cv99-64h7): the address names the card AND this
// recipient, and expires, so a reply is attributed to the person it was
// sent to - never to whatever From address the reply claims.
replyTo: (cardId, userId) => {
const secret = process.env.INBOUND_EMAIL_HMAC_SECRET, domain = process.env.INBOUND_EMAIL_DOMAIN;
if (!cardId || !userId || !secret || !domain) return '';
try { return buildReplyToAddress({ cardId, userId, secret, domain }); } catch (error) { return ''; }
},
});
const receiptPolicy = emailReceiptPolicy();
export const maintainEmailReceipts = createEmailReceiptMaintenance({
jobs: EmailJobs.rawCollection(), commands: EmailCommands.rawCollection(), days: receiptPolicy.days,
});
Meteor.startup(async () => {
await ensureIndex(EmailJobs, { state: 1, nextAttemptAt: 1, _id: 1 });
await ensureIndex(EmailJobs, { userId: 1, state: 1, createdAt: 1, _id: 1 });
await ensureIndex(EmailControls, { paused: 1, _id: 1 });
await ensureIndex(EmailJobs, { state: 1, compactReceiptVersion: 1, finishedAt: 1, _id: 1 });
await ensureIndex(EmailCommands, { status: 1, compactReceiptVersion: 1, finishedAt: 1, _id: 1 });
async function maintainReceipts() {
try { await maintainEmailReceipts(); }
catch (error) { console.error('Email receipt maintenance failed; replay protection retained'); }
finally { Meteor.setTimeout(maintainReceipts, receiptPolicy.intervalMs); }
}
Meteor.setTimeout(maintainReceipts, receiptPolicy.intervalMs);
await ensureIndex(Meteor.users, { 'profile.emailBuffer.0': 1 });
// Polling discovers both new jobs and pre-restart work. Schedule after each
// pass so a slow SMTP server cannot accumulate overlapping scans.
async function scan() {
try {
const users = await Meteor.users.find({ 'profile.emailBuffer.0': { $exists: true } },
{ fields: { 'profile.emailBuffer': 1, 'profile.language': 1 }, limit: 100 }).fetchAsync();
for (const user of users) {
try {
await migrateLegacyEmailBuffer(emailOutbox, user, (id, texts) => Meteor.users.rawCollection()
.updateOne({ _id: id }, { $pullAll: { 'profile.emailBuffer': texts } }));
} catch (error) {
console.error('Legacy email buffer migration failed; original text retained');
}
}
await emailOutbox.drain();
} catch (error) {
console.error('Email outbox scan failed; pending mail will be retried');
} finally {
Meteor.setTimeout(scan, 1000);
}
}
await scan();
});