Nodemailer from 3.0.0 before 10.0.10 contains a quadratic complexity denial of service vulnerability in the SMTP client reply parser in SMTPConnection.onData and isPartialResponse. A malicious SMTP server or on-path attacker can stream continuation lines without a completion line before authentication, blocking the Node.js event loop and exhausting memory.
Summary
When nodemailer DKIM-signs an outbound message, its DKIM message parser unfolds RFC 5322 header continuation lines with a loop that concatenates each continuation line onto the preceding line and then re-tests the anchored regex /^[ \t]/ against the growing merged line on every iteration. Re-testing the regex against the ever-growing accumulated line forces a full string flatten proportional to the accumulated length on each iteration, yielding O(n^2) CPU in the number of continuation lines. An application user who influences the size of a header that folds into many continuation lines (most naturally a large recipient list, but also a long custom header, Subject, or References) can drive tens of thousands of continuation lines and block the single-threaded Node.js event loop for seconds during signing, a repeatable denial of service.
Root Cause
The invariant that signing a message performs work linear in the message size is violated in the header-unfolding step. In src/dkim/message-parser.ts, parseHeaders() splits the buffered header block into lines and iterates backward; for each line matching the continuation pattern /^[ \t]/, it does lines[i - 1] += '\n' + lines[i] and lines.splice(i, 1). The dominant cost is not the array splice: iterating backward keeps each splice near the shrinking tail, so it shifts only the few trailing header lines. The quadratic cost is the anchored regex test /^[ \t]/.test(lines[i]) (together with the += concatenation) evaluated against the growing merged line on every iteration. The += builds an O(1) rope, but the next iteration's regex test forces a full flatten of the entire accumulated line, so the total cost is the sum over all continuation lines, which is O(n^2). The header block is buffered by checkHeaders without any size or line-count cap; the DKIM signer's MAXMESSAGESIZE and cacheTreshold knobs gate the body stream only, not the header block, so nothing bounds the number of continuation lines fed to the loop.
text Affected file and function (verified at the published v10.0.9 artifact, in src/ and compiled verbatim into the published dist output): - src/dkim/message-parser.ts: MessageParser.parseHeaders (the continuation-unfold loop that re-tests /^[ \t]/ against the growing merged line)
Impact
An attacker or user who can make an outbound, DKIM-signed message carry a header that folds into a large number of continuation lines can freeze the sending Node.js process during signing. Because Node.js is single-threaded, the synchronous unfold loop starves the entire event loop, halting all other work in the process, and it is repeatable on every such message. The natural lever is a large recipient list: nodemailer's own MIME composer folds a To or Cc value at column 76 into space-prefixed continuation lines, and the count scales linearly with the number of recipients, so a caller-supplied recipient list (common in bulk-mail, notification, and multi-tenant email APIs) turns into tens of thousands of continuation lines. The single precondition is that DKIM signing is enabled, which is a mainstream deliverability configuration. Independent reproduction on Node.js 24 measured roughly 2.8 seconds of event-loop blocking at about 20,000 continuation lines and roughly 11.5 seconds at about 40,000, scaling quadratically; the full composer-to-signer chain with a 60,000-recipient To header blocked for roughly 6.6 seconds. The applications that cap recipient count or header size shrink the exposed population but do not change the per-message availability impact once a large header is accepted.
Proof of Concept
Node.js 24; the shipped DKIM signer (require('nodemailer/lib/dkim')) or the exact unfold loop.
Steps: (1) construct a message whose header block contains one header value folded into many space-prefixed continuation lines (for example by supplying a very large recipient list, which nodemailer's MIME composer folds automatically); (2) DKIM-sign it and observe the event loop stall while parseHeaders unfolds the block. A minimal microbenchmark of the exact unfold logic demonstrates the complexity:
js // Reproduces the parseHeaders unfold loop verbatim (Node 24). function unfold(headerBlock) { const lines = headerBlock.split(/\r?\n/); for (let i = lines.length - 1; i > 0; i--) { if (/^[ \t]/.test(lines[i])) { lines[i - 1] += '\n' + lines[i]; lines.splice(i, 1); } } return lines; } function run(n) { let block = 'To: a@b.c\r\n'; for (let i = 0; i < n; i++) block += ' cont-' + i + '@example.com,\r\n'; for (let k = 0; k < 5; k++) block += 'X-H' + k + ': v\r\n'; const t = Date.now(); unfold(block); return Date.now() - t; } for (const n of [5000, 10000, 20000, 40000]) console.log(n, run(n) + 'ms');
text 5000 27ms 10000 542ms 20000 2853ms 40000 11503ms (2x input yields roughly 4x-5x time: quadratic. The cost is the regex re-flatten of the growing merged line, not the splice.)
Attack Chain
1. Exposure: An application DKIM-signs outbound mail (a mainstream deliverability configuration, enabled per transport or per message) for a message whose header size is influenced by a user, for example a large recipient list, a long custom header, Subject, or References. 2. Control: The attacker or user controls the size of that header. The MIME composer folds it deterministically at column 76 into space-prefixed continuation lines that match the continuation pattern, so the continuation-line count scales linearly with the supplied size. 3. Path: Signing pipes the composed message through the DKIM MessageParser; checkHeaders buffers the whole header block into rawHeaders and calls parseHeaders(), the single sink, on every signed message. 4. Guard: No header-size or line-count cap exists between the input and the sink; the signer's body-only size thresholds do not apply to the header block. 5. Primitive: The unfold loop re-tests the anchored regex against the growing merged line on each continuation line, forcing a full flatten per iteration and yielding O(n^2) synchronous CPU. 6. Result: Event-loop starvation of the single-threaded sending process for an attacker-scaled duration, repeatable per message: a denial of service.
Bypass Evidence
The relevant guard would be a cap on header-block size or continuation-line count before unfolding. A search of the DKIM module confirms none exists: checkHeaders accumulates header chunks unbounded until the header terminator, and the only size knobs (MAXMESSAGESIZE, cacheTreshold) are checked against the body stream, not the header block. The strongest disproof attempt was that the backward splice makes the loop cheap for a single consecutive folded block (so it would not be quadratic); this was refuted by a mechanism-isolation benchmark: removing the splice entirely leaves the loop just as slow (about 11 seconds at 40,000 lines), while precomputing the continuation test on the original lines so the growing merged line is never re-tested collapses it to a few milliseconds. This proves the quadratic driver is the regex re-flatten of the accumulated line, not the array shift, and confirms the loop is quadratic even for a single consecutive folded block. No published advisory covers this file: the disclosed complexity issues all live in the address parser and recipient-normalization code, and the DKIM message parser has never received a complexity fix.
Affected Versions
- Ecosystem: npm - Package: nodemailer - Confirmed affected range: <= 10.0.9 - Latest release checked: nodemailer 10.0.9 (npm registry; vulnerable code verified at git tag v10.0.9 and in the published dist output) - Fix status: not fixed (no released version removes the quadratic unfold or caps header size)
The unfold loop is long-standing DKIM code that predates the address-parser complexity fix family, so the exact introducing release is not positively established and the lower bound is left open; the upper bound is verified against the current published artifact, which is vulnerable with no fix.
Suggested Fix
Enforce linear-time header unfolding and bound the header block. The key correction is to stop re-scanning the growing accumulated line: classify each line's continuation status on the original split lines before merging, and build the unfolded value with an array plus a single join rather than repeatedly re-testing and concatenating the growing string. Simply replacing splice with a filter or two-pointer compaction while still re-testing the merged line would not fix the issue, because the regex re-flatten of the accumulated line is the quadratic driver. Independently, impose a configurable maximum on the buffered header-block size or continuation-line count in the message parser and fail closed when it is exceeded, so an oversized folded header cannot force unbounded work. As an interim mitigation, applications should cap recipient counts and header-value sizes for messages that will be DKIM-signed.
Reported by zx (GitHub: @manus-pi).
Nodemailer from 3.0.0 before 10.0.13 contains an improper input validation vulnerability in its address parser that fails to strip RFC 5322 comments inside angle-bracket addresses. Attackers can supply recipients like a display name with a parenthesized comment in the domain, so illegal characters reach envelope.to and RCPT TO, causing rejected delivery or parser interpretation conflicts that bypass domain allow-lists.
Nodemailer 3.0.0 before 10.0.13 has a regular expression denial of service in SMTPConnection.actionEHLO, whose four AUTH mechanism detection regexes contain overlapping whitespace sub-patterns that backtrack quadratically. A malicious or man-in-the-middle SMTP server can reply to EHLO with 250-AUTH, a long whitespace run and a non-matching token, blocking the Node.js event loop for tens of seconds to hours before authentication.
Nodemailer before 10.0.2 fails to properly flatten deeply nested arrays in recipient fields such as to, cc, and bcc, allowing attackers to cause stack exhaustion. Attackers can supply a deeply nested JSON recipient array that triggers recursive Array.toString() conversion, exhausting the call stack and terminating the Node.js process.
Nodemailer versions 5.0.0 through 10.0.1 use a process-global DNS cache that is keyed only by the DNS host, while each cache entry also stores the caller-specific TLS servername. When two direct TLS/SMTPS transports (secure: true) resolve the same non-IP host with different tls.servername values, the first transport's servername is returned on the cache hit and overwrites the second transport's explicitly configured value, so Nodemailer sends the wrong SNI value and validates the peer certificate against the wrong identity. In multi-tenant services or SNI-routed SMTP gateways, an attacker who can prime the cache can cause a victim transport to connect to the attacker's TLS virtual host and accept the attacker's certificate even with rejectUnauthorized: true, disclosing the victim's SMTP credentials. Fixed in 10.0.2.
nodemailer before 10.0.6 contains a denial of service vulnerability in the addressparser free-text fallback regex pattern that exhibits quadratic backtracking behavior. Attackers can supply crafted email header values with long whitespace-free runs to block the Node.js event loop for tens of seconds, causing service unavailability.
Nodemailer is a Node.js email-sending library. In versions >= 9.1.0 and < 10.0.9, the address parser (src/addressparser) mishandles addresses whose local-part is a quoted string and that are followed by RFC 5322 comments, allowing trailing comment-separated domain atoms to be retained in the normalized address. For example, the input "user"@example.com(x)evil.com is parsed to the address value 'user@example.com evil.com', which contains additional attacker-controlled domain text separated by a literal space. This parsed value is used without further strict recipient validation when the message envelope is built (envelope.to in src/mime-node), so a malformed/ambiguous recipient address can be accepted and placed in the SMTP envelope. Whether this results in delivery to an unintended recipient on real SMTP servers has not been confirmed. The issue is a variant of the RFC 5322 comment parsing problem addressed in GHSA-cc9r-2j5m-2m83, affecting the separate quoted-local-part code path. Version 10.0.9 contains a fix.
Nodemailer before 9.1.0 fails to apply UTS-46 normalization when encoding international domain names, causing the domain resolver to compute a different Punycode A-label than standards-compliant parsers. Attackers can craft recipient addresses with invisible characters or compatibility mappings that pass domain allow-list checks but are delivered to attacker-controlled domains via SMTP.
Nodemailer before 9.1.0 contains a quadratic time complexity vulnerability in the addressparser component that allows remote attackers to cause denial of service by supplying a crafted comma-separated address list. Attackers can send a single email with a large number of addresses to block the Node.js event loop for extended periods, consuming 100% CPU and freezing the process.
Nodemailer (npm package nodemailer) versions 9.1.0 and earlier do not honor the disableFileAccess and disableUrlAccess sandbox options when message content is resolved through the public plugin API MailMessage.resolveContent() using the documented legacy three-argument signature resolveContent(data, key, callback). Because shared.resolveContent() normalizes the missing options argument to an empty object, the message-level flags copied into mail.data by the MailMessage constructor are discarded, and resolveContentValue() skips both access-control checks, reaching nmfetch(url) or fs.createReadStream(path). As a result, plugin or application code that resolves untrusted message content (html, text, attachment path or href) via this API can be induced to read arbitrary local files or issue outbound HTTP(S) requests (server-side request forgery), bypassing the sandbox the application enabled. The internal paths used by transporter.sendMail() (resolveAll(), convertDataImages(), and the MIME streaming path) are not affected. Fixed in version 9.1.1.
Nodemailer versions 9.1.0 through 10.0.4 contain a quadratic time complexity vulnerability in the addressparser component when parsing email addresses with RFC 5322 comments. Attackers can craft malicious email headers with comment-separated atoms to consume excessive CPU and block the Node.js event loop for several seconds, causing denial of service.
Nodemailer before 8.0.4 is vulnerable to SMTP command injection through the unsanitized envelope.size parameter. When an application passes a custom envelope object with a size property containing CRLF characters to sendMail(), the value is concatenated into the SMTP MAIL FROM command (as SIZE=...) without sanitization, allowing injection of arbitrary SMTP commands such as RCPT TO to silently add attacker-controlled recipients. Exploitation requires the application to expose the envelope size to attacker-controlled input, as Nodemailer does not include size in the default auto-constructed envelope.
Nodemailer before 8.0.8 disables TLS certificate verification in lib/fetch/index.js through rejectUnauthorized: false, allowing attackers to intercept OAuth2 token requests. Attackers in a machine-in-the-middle position can capture OAuth client secrets, refresh tokens, and access tokens transmitted over compromised HTTPS connections.
Nodemailer before 8.0.9 fails to sanitize carriage return and line feed characters in list comment fields, allowing attackers to inject arbitrary message headers. An attacker with control over list..comment parameters can inject CRLF sequences to create additional headers in generated RFC822 messages, altering mail client behavior and message semantics.
Nodemailer before 8.0.9 fails to enforce disableFileAccess and disableUrlAccess options during message normalization in jsonTransport. Attackers can read local files or fetch URLs by supplying path or href values in message content fields, bypassing intended access controls.
nodemailer before 9.0.1 fails to apply disableFileAccess and disableUrlAccess flags to message-level raw option, allowing authenticated attackers to read arbitrary files or perform server-side request forgery by supplying path or href properties. Attackers can exploit this by crafting raw messages with file paths or URLs that bypass the intended sandbox, with fetched content delivered in the outgoing message to attacker-controlled recipients.
nodemailer before 6.9.9 contains a regular expression denial of service vulnerability in email parsing when attachDataUrls parameter is set or processing embedded file attachments. Attackers can send specially crafted emails with malicious data URLs or embedded attachments to cause the event loop to hang and deny service.
Summary A DoS can occur that immediately halts the system due to the use of an unsafe function.
Details According to RFC 5322, nested group structures (a group inside another group) are not allowed. Therefore, in lib/addressparser/index.js, the email address parser performs flattening when nested groups appear, since such input is likely to be abnormal. (If the address is valid, it is added as-is.) In other words, the parser flattens all nested groups and inserts them into the final group list. However, the code implemented for this flattening process can be exploited by malicious input and triggers DoS
RFC 5322 uses a colon (:) to define a group, and commas (,) are used to separate members within a group. At the following location in lib/addressparser/index.js:
https://github.com/nodemailer/nodemailer/blob/master/lib/addressparser/index.js#L90
there is code that performs this flattening. The issue occurs when the email address parser attempts to process the following kind of malicious address header:
g0: g1: g2: g3: ... gN: victim;
Because no recursion depth limit is enforced, the parser repeatedly invokes itself in the pattern addressparser → handleAddress → addressparser → ... for each nested group. As a result, when an attacker sends a header containing many colons, Nodemailer enters infinite recursion, eventually throwing Maximum call stack size exceeded and causing the process to terminate immediately. Due to the structure of this behavior, no authentication is required, and a single request is enough to shut down the service.
The problematic code section is as follows: js if (isGroup) { ... if (data.group.length) { let parsedGroup = addressparser(data.group.join(',')); // <- boom! parsedGroup.forEach(member => { if (member.group) { groupMembers = groupMembers.concat(member.group); } else { groupMembers.push(member); } }); } } data.group is expected to contain members separated by commas, but in the attacker’s payload the group contains colon (:) tokens. Because of this, the parser repeatedly triggers recursive calls for each colon, proportional to their number.
PoC
const nodemailer = require('nodemailer');
function buildDeepGroup(depth) { let parts = []; for (let i = 0; i < depth; i++) { parts.push(g${i}:); } return parts.join(' ') + ' user;'; }
const DEPTH = 3000; // <- control depth const toHeader = buildDeepGroup(DEPTH); console.log('to header length:', toHeader.length);
const transporter = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'unix' });
console.log('parsing start');
transporter.sendMail( { from: 'test', to: toHeader, subject: 'test', text: 'test' }, (err, info) => { if (err) { console.error('error:', err); } else { console.log('finished :', info && info.envelope); } } ); As a result, when the colon is repeated beyond a certain threshold, the Node.js process terminates immediately.
Impact The attacker can achieve the following:
1. Force an immediate crash of any server/service that uses Nodemailer 2. Kill the backend process with a single web request 3. In environments using PM2/Forever, trigger a continuous restart loop, causing severe resource exhaustion”
Summary A DoS can occur that immediately halts the system due to the use of an unsafe function.
Details According to RFC 5322, nested group structures (a group inside another group) are not allowed. Therefore, in lib/addressparser/index.js, the email address parser performs flattening when nested groups appear, since such input is likely to be abnormal. (If the address is valid, it is added as-is.) In other words, the parser flattens all nested groups and inserts them into the final group list. However, the code implemented for this flattening process can be exploited by malicious input and triggers DoS
RFC 5322 uses a colon (:) to define a group, and commas (,) are used to separate members within a group. At the following location in lib/addressparser/index.js:
https://github.com/nodemailer/nodemailer/blob/master/lib/addressparser/index.js#L90
there is code that performs this flattening. The issue occurs when the email address parser attempts to process the following kind of malicious address header:
g0: g1: g2: g3: ... gN: victim;
Because no recursion depth limit is enforced, the parser repeatedly invokes itself in the pattern addressparser → handleAddress → addressparser → ... for each nested group. As a result, when an attacker sends a header containing many colons, Nodemailer enters infinite recursion, eventually throwing Maximum call stack size exceeded and causing the process to terminate immediately. Due to the structure of this behavior, no authentication is required, and a single request is enough to shut down the service.
The problematic code section is as follows: js if (isGroup) { ... if (data.group.length) { let parsedGroup = addressparser(data.group.join(',')); // <- boom! parsedGroup.forEach(member => { if (member.group) { groupMembers = groupMembers.concat(member.group); } else { groupMembers.push(member); } }); } } data.group is expected to contain members separated by commas, but in the attacker’s payload the group contains colon (:) tokens. Because of this, the parser repeatedly triggers recursive calls for each colon, proportional to their number.
PoC
const nodemailer = require('nodemailer');
function buildDeepGroup(depth) { let parts = []; for (let i = 0; i < depth; i++) { parts.push(g${i}:); } return parts.join(' ') + ' user;'; }
const DEPTH = 3000; // <- control depth const toHeader = buildDeepGroup(DEPTH); console.log('to header length:', toHeader.length);
const transporter = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'unix' });
console.log('parsing start');
transporter.sendMail( { from: 'test', to: toHeader, subject: 'test', text: 'test' }, (err, info) => { if (err) { console.error('error:', err); } else { console.log('finished :', info && info.envelope); } } ); As a result, when the colon is repeated beyond a certain threshold, the Node.js process terminates immediately.
Impact The attacker can achieve the following:
1. Force an immediate crash of any server/service that uses Nodemailer 2. Kill the backend process with a single web request 3. In environments using PM2/Forever, trigger a continuous restart loop, causing severe resource exhaustion”
A vulnerability was identified in the email parsing library due to improper handling of specially formatted recipient email addresses. An attacker can exploit this flaw by crafting a recipient address that embeds an external address within quotes. This causes the application to misdirect the email to the attacker's external address instead of the intended internal recipient. This could lead to a significant data leak of sensitive information and allow an attacker to bypass security filters and access controls.