Files
wekan/server/lib/mailTransport.js
T
Lauri Ojansivu 032722fcc4 Security: trust a certificate instead of disabling verification, and escape every metacharacter.
CodeQL alert #430, js/disabling-certificate-validation, High:
`reqOptions.rejectUnauthorized = false` in the outgoing-webhook path. It is
right, and the switch is gone.

`rejectUnauthorized: false` accepts ANY certificate - including the one a man in
the middle presents - which is the attack the handshake exists to stop. What
#6553 and #6551 actually need is not "verify nothing", it is "this certificate is
legitimate", so that is what WeKan takes now:

  WEBHOOK_TLS_CA_CERT   the certificate (or CA) to TRUST for outgoing webhooks
  MAIL_TLS_CA_CERT      the same for the mail server
  MAIL_TLS_SERVERNAME   the name to verify the mail certificate AGAINST, for the
                        wildcard-one-level-short case the report describes

Each is the PEM itself or a path to a file holding it. A self-signed certificate
is its own issuer, so naming it here is exactly what makes it valid - and
verification stays ON, the chain is still checked, the hostname is still checked.
A path that cannot be read is not fatal: it logs which setting failed and keeps
the system trust store, rather than stopping mail or webhooks.

The SSRF protections are untouched: the address is still resolved once and
pinned, private ranges are still refused, redirects are still blocked.

CodeQL alert #429, js/incomplete-sanitization, High:
`helper.replace(/\./g, '\\.')` in a test escaped dots only, so a backslash in the
value could change the meaning of the pattern it was spliced into. It uses the
same escape-everything helper tests/testsAreRegistered.test.cjs already has, with
the backslash escaped FIRST.

tests/mailTransportTls.test.cjs now fails if `rejectUnauthorized: false`, that
same assignment, or NODE_TLS_REJECT_UNAUTHORIZED appears in either file - so the
pattern cannot come back quietly - and covers the certificate-from-PEM,
certificate-from-path and unreadable-path cases.

Thanks to GitHub CodeQL code scanning and xet7 !
2026-07-28 17:59:17 +03:00

116 lines
4.9 KiB
JavaScript

// ============================================================================
// The SMTP transport, when the certificate cannot be verified as it stands
// (#6551).
//
// "Error trying to send email: Hostname/IP doesn't match certificate's altnames"
// is a mail server whose certificate does not match the name it is reached by - a
// wildcard that covers one level fewer than the host has, an internal CA, a
// self-signed certificate. Meteor builds its transport from MAIL_URL and offers
// no way to say anything about it, so such a server could not be used at all.
//
// The first answer here was `rejectUnauthorized: false`, which accepts ANY
// certificate - including one a man in the middle presents - and is what the TLS
// handshake exists to prevent (CodeQL js/disabling-certificate-validation). It is
// gone. What is offered instead says exactly what is actually true about the
// server, and keeps verification ON:
//
// MAIL_TLS_CA_CERT the certificate (or CA) WeKan should TRUST for this
// server: the PEM itself, or a path to a file holding it.
// A self-signed certificate is its own issuer, so putting
// it here is what makes it valid.
// MAIL_TLS_SERVERNAME the name to verify the certificate AGAINST, when the
// host WeKan connects to is not the name on it - the
// wildcard-one-level-short case from the report.
//
// Both are opt-in and neither weakens anything for anyone who does not set them.
// smtpOptionsFromUrl is pure, so tests/mailTransportTls.test.cjs can check the
// parsing without an SMTP server; the wiring below needs one and is not exercised
// by the test suite.
// ============================================================================
import fs from 'fs';
// A certificate from an env var: the PEM itself, or a path to a file holding it.
// Never fatal - a bad path leaves the system trust store in place and says so,
// rather than stopping mail from being sent at all.
export function certificateFrom(value, { name = 'certificate', readFile = fs.readFileSync } = {}) {
const text = String(value || '').trim();
if (!text) return null;
if (text.includes('-----BEGIN CERTIFICATE-----')) return text;
try {
return readFile(text, 'utf8');
} catch (error) {
// eslint-disable-next-line no-console
console.error(
`${name}: cannot read ${text} (${error.message}). The system trust store is ` +
'used instead, so a server with a private certificate will still be refused.',
);
return null;
}
}
// The nodemailer options for a MAIL_URL, as Meteor's own transport would build
// them - plus whatever the operator said about the certificate.
export function smtpOptionsFromUrl(mailUrl, { ca = null, servername = '' } = {}) {
const url = new URL(mailUrl);
if (url.protocol !== 'smtp:' && url.protocol !== 'smtps:') {
throw new Error(`MAIL_URL protocol must be smtp: or smtps:, got ${url.protocol}`);
}
const secure = url.protocol === 'smtps:';
const options = {
host: url.hostname,
// The ports SMTP actually uses: 465 is implicit TLS, 587 is STARTTLS.
port: url.port ? Number(url.port) : (secure ? 465 : 587),
secure,
// Meteor defaults the connection pool on; keep the same behaviour.
pool: true,
// Verification stays ON. Only the inputs to it can be adjusted below.
tls: { rejectUnauthorized: true },
};
if (ca) options.tls.ca = ca;
if (servername) options.tls.servername = servername;
if (url.username) {
options.auth = {
// A password with @ / : / % in it arrives percent-encoded in the URL.
user: decodeURIComponent(url.username),
pass: decodeURIComponent(url.password || ''),
};
}
return options;
}
// True when the operator told WeKan something about the mail certificate.
export function hasTlsOverrides(env = process.env) {
return Boolean((env.MAIL_TLS_CA_CERT || '').trim() || (env.MAIL_TLS_SERVERNAME || '').trim());
}
// Install the custom transport when there is something to say, and only then.
// Returns what it did, so the caller can log it.
export function installMailTransport({ Email, EmailInternals, env = process.env } = {}) {
if (!hasTlsOverrides(env)) return 'default';
if (!env.MAIL_URL) return 'no-mail-url';
if (!Email || !EmailInternals) return 'no-email-package';
const nodemailer = EmailInternals?.NpmModules?.nodemailer?.module;
if (!nodemailer) return 'no-nodemailer';
const transport = nodemailer.createTransport(
smtpOptionsFromUrl(env.MAIL_URL, {
ca: certificateFrom(env.MAIL_TLS_CA_CERT, { name: 'MAIL_TLS_CA_CERT' }),
servername: (env.MAIL_TLS_SERVERNAME || '').trim(),
}),
);
// Meteor hands the message plus its own packageSettings; nodemailer takes the
// message fields as they are and would choke on the extra key.
Email.customTransport = ({ packageSettings, ...message }) => transport.sendMail(message);
return 'custom-tls';
}