Skip to content

Commit 6a947ac

Browse files
andris9claude
andcommitted
fix!: validate TLS certificates by default when fetching remote content
lib/fetch hardcoded rejectUnauthorized:false, so every HTTPS request — including remote attachment fetches that carry Authorization/API-key headers via attachment.httpHeaders — skipped certificate validation. A network-adjacent attacker could present any certificate (self-signed, expired, wrong host) and silently harvest those credentials. Validate certificates by default everywhere. Callers opt out explicitly with tls.rejectUnauthorized=false, and attachments can pass a per-message `tls` option for legitimate internal/self-signed hosts. Also harden two adjacent paths flagged while mapping the fetch flow: - strip Authorization/Cookie/Proxy-Authorization request headers when a redirect crosses to a different host or downgrades https->http - validate the HTTPS proxy CONNECT certificate by default, overridable via the transport tls options (e.g. self-signed proxy in tests) Refs: GHSA-55pm-vh62-rwjg BREAKING CHANGE: HTTPS requests made while fetching remote content (attachment href/path URLs, OAuth2 token endpoints, HTTP/HTTPS proxy CONNECT) now validate the server's TLS certificate by default. Requests to hosts with self-signed, expired, or hostname-mismatched certificates that previously succeeded will now fail. Opt back out per request with tls.rejectUnauthorized=false (transport options, or a per-attachment `tls` option). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent e3b1bda commit 6a947ac

11 files changed

Lines changed: 381 additions & 22 deletions

File tree

‎lib/fetch/index.js‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,10 @@ function nmfetch(url, options) {
123123
path: parsed.path,
124124
port: parsed.port ? parsed.port : parsed.protocol === 'https:' ? 443 : 80,
125125
headers,
126-
rejectUnauthorized: false,
126+
// Validate TLS certificates by default. Callers that genuinely need to
127+
// reach a self-signed/internal host opt out explicitly with
128+
// options.tls = { rejectUnauthorized: false }.
129+
rejectUnauthorized: true,
127130
agent: false
128131
};
129132

@@ -212,7 +215,27 @@ function nmfetch(url, options) {
212215
// redirect does not include POST body
213216
options.method = 'GET';
214217
options.body = false;
215-
return nmfetch(urllib.resolve(url, res.headers.location), options);
218+
219+
const redirectUrl = urllib.resolve(url, res.headers.location);
220+
const redirectParsed = urllib.parse(redirectUrl);
221+
222+
// Do not forward credentials when the redirect leaves the original
223+
// security context: a different host, or a downgrade from https to
224+
// http (which would otherwise put them on the wire in cleartext).
225+
// Strip sensitive request headers so an attacker who controls the
226+
// redirect target cannot harvest them.
227+
const crossHost = redirectParsed.hostname !== parsed.hostname;
228+
const downgrade = parsed.protocol === 'https:' && redirectParsed.protocol === 'http:';
229+
if (options.headers && (crossHost || downgrade)) {
230+
const sensitive = ['authorization', 'cookie', 'proxy-authorization'];
231+
Object.keys(options.headers).forEach(key => {
232+
if (sensitive.includes(key.toLowerCase())) {
233+
delete options.headers[key];
234+
}
235+
});
236+
}
237+
238+
return nmfetch(redirectUrl, options);
216239
}
217240

218241
fetchRes.statusCode = res.statusCode;

‎lib/mail-composer/index.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ class MailComposer {
142142
} else if (attachment.href) {
143143
data.content = {
144144
href: attachment.href,
145-
httpHeaders: attachment.httpHeaders
145+
httpHeaders: attachment.httpHeaders,
146+
tls: attachment.tls
146147
};
147148
} else {
148149
data.content = attachment.content || '';

‎lib/mailer/index.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ class Mail extends EventEmitter {
324324
// Connect using a HTTP CONNECT method
325325
case 'http':
326326
case 'https':
327-
httpProxyClient(proxy.href, options.port, options.host, (err, socket) => {
327+
httpProxyClient(proxy.href, options.port, options.host, this.options.tls || {}, (err, socket) => {
328328
if (err) {
329329
return callback(err);
330330
}

‎lib/mime-node/index.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1006,7 +1006,7 @@ class MimeNode {
10061006
return contentStream;
10071007
}
10081008
// fetch URL
1009-
return nmfetch(content.href, { headers: content.httpHeaders });
1009+
return nmfetch(content.href, { headers: content.httpHeaders, tls: content.tls });
10101010
}
10111011

10121012
// pass string or buffer content as a stream

‎lib/nodemailer.js‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,10 @@ module.exports.createTestAccount = function (apiUrl, callback) {
102102
body: Buffer.from(JSON.stringify(requestBody))
103103
};
104104

105-
// Credential-bearing request — opt back into strict cert validation when
106-
// the API URL is HTTPS. lib/fetch defaults to rejectUnauthorized:false
107-
// for attachment hosts that may be self-signed; the Ethereal API has a
108-
// real cert, so the lax default was a free attack surface.
105+
// Credential-bearing request to the Ethereal API. lib/fetch already
106+
// validates certs by default; pin rejectUnauthorized:true here so this
107+
// call stays strict regardless of any future default change and is never
108+
// relaxed for a real-cert endpoint.
109109
if (/^https:/i.test(apiUrl)) {
110110
fetchOptions.tls = { rejectUnauthorized: true };
111111
}

‎lib/shared/index.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ function resolveContentValue(data, key, options, callback) {
569569
callback(err);
570570
});
571571
}
572-
return resolveStream(nmfetch(content.path || content.href), callback);
572+
return resolveStream(nmfetch(content.path || content.href, { headers: content.httpHeaders, tls: content.tls }), callback);
573573
} else if (/^data:/i.test(content.path || content.href)) {
574574
const parsedDataUri = module.exports.parseDataURI(content.path || content.href);
575575

‎lib/smtp-connection/http-proxy-client.js‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,29 @@ const errors = require('../errors');
1919
* @param {String} proxyUrl proxy configuration, etg "http://proxy.host:3128/"
2020
* @param {Number} destinationPort Port to open in destination host
2121
* @param {String} destinationHost Destination hostname
22+
* @param {Object} [tlsOptions] Optional TLS options for an HTTPS proxy (e.g. { rejectUnauthorized: false })
2223
* @param {Function} callback Callback to run with the rocket object once connection is established
2324
*/
24-
function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) {
25+
function httpProxyClient(proxyUrl, destinationPort, destinationHost, tlsOptions, callback) {
26+
if (typeof tlsOptions === 'function') {
27+
callback = tlsOptions;
28+
tlsOptions = {};
29+
}
30+
tlsOptions = tlsOptions || {};
31+
2532
const proxy = urllib.parse(proxyUrl);
2633

27-
const options = {
34+
const connectOptions = {
2835
host: proxy.hostname,
2936
port: Number(proxy.port) ? Number(proxy.port) : proxy.protocol === 'https:' ? 443 : 80
3037
};
3138

3239
let connect;
3340
if (proxy.protocol === 'https:') {
34-
// we can use untrusted proxies as long as we verify actual SMTP certificates
35-
options.rejectUnauthorized = false;
41+
// Validate the proxy's TLS certificate by default. A caller that uses a
42+
// self-signed proxy (e.g. integration tests) opts out explicitly with
43+
// tls.rejectUnauthorized === false.
44+
connectOptions.rejectUnauthorized = tlsOptions.rejectUnauthorized !== false;
3645
connect = tls.connect.bind(tls);
3746
} else {
3847
connect = net.connect.bind(net);
@@ -62,7 +71,7 @@ function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) {
6271
tempSocketErr(err);
6372
};
6473

65-
socket = connect(options, () => {
74+
socket = connect(connectOptions, () => {
6675
if (finished) {
6776
return;
6877
}

‎lib/xoauth2/index.js‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -378,12 +378,11 @@ class XOAuth2 extends Stream {
378378
allowErrorResponse: true
379379
};
380380

381-
// OAuth2 token endpoints are credential-bearing. lib/fetch defaults to
382-
// rejectUnauthorized:false (intentional for self-signed attachment
383-
// hosts), so opt back in to strict cert validation here when the
384-
// access URL is HTTPS. params.tls (the user's options.tls) is layered
385-
// on top so callers with a self-hosted provider on a private CA can
386-
// still override.
381+
// OAuth2 token endpoints are credential-bearing. lib/fetch already
382+
// validates certs by default; pin rejectUnauthorized:true here so the
383+
// token fetch stays strict, while still layering params.tls (the
384+
// user's options.tls) on top so callers with a self-hosted provider on
385+
// a private CA can override.
387386
if (/^https:/i.test(url)) {
388387
fetchOptions.tls = Object.assign({ rejectUnauthorized: true }, params.tls || {});
389388
}

‎test/fetch/nmfetch-test.js‎

Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,30 @@ describe('NMFetch Tests', { timeout: 50 * 1000 }, () => {
174174

175175
break;
176176
}
177+
178+
case '/crosshost':
179+
// redirect to a different hostname (127.0.0.1 vs localhost)
180+
res.writeHead(302, {
181+
Location: 'http://127.0.0.1:' + HTTP_PORT + '/show-auth'
182+
});
183+
res.end();
184+
break;
185+
186+
case '/samehost':
187+
// redirect within the same hostname
188+
res.writeHead(302, {
189+
Location: '/show-auth'
190+
});
191+
res.end();
192+
break;
193+
194+
case '/show-auth':
195+
res.writeHead(200, {
196+
'Content-Type': 'text/plain'
197+
});
198+
res.end(req.headers.authorization || 'NO_AUTH');
199+
break;
200+
177201
default:
178202
res.writeHead(200, {
179203
'Content-Type': 'text/plain'
@@ -183,6 +207,14 @@ describe('NMFetch Tests', { timeout: 50 * 1000 }, () => {
183207
});
184208

185209
httpsServer = https.createServer(httpsOptions, (req, res) => {
210+
if (req.url === '/downgrade') {
211+
// redirect to plain HTTP on the same host
212+
res.writeHead(302, {
213+
Location: 'http://localhost:' + HTTP_PORT + '/show-auth'
214+
});
215+
res.end();
216+
return;
217+
}
186218
res.writeHead(200, {
187219
'Content-Type': 'text/plain'
188220
});
@@ -213,7 +245,12 @@ describe('NMFetch Tests', { timeout: 50 * 1000 }, () => {
213245
});
214246

215247
it('should fetch HTTPS data', (t, done) => {
216-
let req = nmfetch('https://localhost:' + HTTPS_PORT);
248+
// test server uses a self-signed cert, so opt out of validation here
249+
let req = nmfetch('https://localhost:' + HTTPS_PORT, {
250+
tls: {
251+
rejectUnauthorized: false
252+
}
253+
});
217254
let buf = [];
218255
req.on('data', chunk => {
219256
buf.push(chunk);
@@ -497,4 +534,82 @@ describe('NMFetch Tests', { timeout: 50 * 1000 }, () => {
497534
});
498535
req.on('end', () => {});
499536
});
537+
538+
it('should reject a self-signed cert by default', (t, done) => {
539+
// no tls option provided — certificates must be validated by default
540+
let req = nmfetch('https://localhost:' + HTTPS_PORT);
541+
req.on('data', () => {});
542+
req.on('error', err => {
543+
assert.ok(err);
544+
done();
545+
});
546+
req.on('end', () => {});
547+
});
548+
549+
it('should allow a self-signed cert when rejectUnauthorized is false', (t, done) => {
550+
let req = nmfetch('https://localhost:' + HTTPS_PORT, {
551+
tls: {
552+
rejectUnauthorized: false
553+
}
554+
});
555+
let buf = [];
556+
req.on('data', chunk => {
557+
buf.push(chunk);
558+
});
559+
req.on('end', () => {
560+
assert.strictEqual(Buffer.concat(buf).toString(), 'Hello World HTTPS\n');
561+
done();
562+
});
563+
});
564+
565+
it('should drop the Authorization header on a cross-host redirect', (t, done) => {
566+
let req = nmfetch('http://localhost:' + HTTP_PORT + '/crosshost', {
567+
headers: {
568+
Authorization: 'Bearer SECRET_TOKEN'
569+
}
570+
});
571+
let buf = [];
572+
req.on('data', chunk => {
573+
buf.push(chunk);
574+
});
575+
req.on('end', () => {
576+
assert.strictEqual(Buffer.concat(buf).toString(), 'NO_AUTH');
577+
done();
578+
});
579+
});
580+
581+
it('should keep the Authorization header on a same-host redirect', (t, done) => {
582+
let req = nmfetch('http://localhost:' + HTTP_PORT + '/samehost', {
583+
headers: {
584+
Authorization: 'Bearer SECRET_TOKEN'
585+
}
586+
});
587+
let buf = [];
588+
req.on('data', chunk => {
589+
buf.push(chunk);
590+
});
591+
req.on('end', () => {
592+
assert.strictEqual(Buffer.concat(buf).toString(), 'Bearer SECRET_TOKEN');
593+
done();
594+
});
595+
});
596+
597+
it('should drop the Authorization header on an https to http downgrade redirect', (t, done) => {
598+
let req = nmfetch('https://localhost:' + HTTPS_PORT + '/downgrade', {
599+
tls: {
600+
rejectUnauthorized: false
601+
},
602+
headers: {
603+
Authorization: 'Bearer SECRET_TOKEN'
604+
}
605+
});
606+
let buf = [];
607+
req.on('data', chunk => {
608+
buf.push(chunk);
609+
});
610+
req.on('end', () => {
611+
assert.strictEqual(Buffer.concat(buf).toString(), 'NO_AUTH');
612+
done();
613+
});
614+
});
500615
});
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
'use strict';
2+
3+
const { describe, it, beforeEach, afterEach } = require('node:test');
4+
const assert = require('node:assert/strict');
5+
const https = require('node:https');
6+
const MimeNode = require('../../lib/mime-node');
7+
8+
// Self-signed cert reused from test/fetch/nmfetch-test.js — keeps this test
9+
// self-contained per the repo's per-file-copy convention.
10+
const httpsOptions = {
11+
key:
12+
'-----BEGIN RSA PRIVATE KEY-----\n' +
13+
'MIIEpAIBAAKCAQEA6Z5Qqhw+oWfhtEiMHE32Ht94mwTBpAfjt3vPpX8M7DMCTwHs\n' +
14+
'1xcXvQ4lQ3rwreDTOWdoJeEEy7gMxXqH0jw0WfBx+8IIJU69xstOyT7FRFDvA1yT\n' +
15+
'RXY2yt9K5s6SKken/ebMfmZR+03ND4UFsDzkz0FfgcjrkXmrMF5Eh5UXX/+9YHeU\n' +
16+
'xlp0gMAt+/SumSmgCaysxZLjLpd4uXz+X+JVxsk1ACg1NoEO7lWJC/3WBP7MIcu2\n' +
17+
'wVsMd2XegLT0gWYfT1/jsIH64U/mS/SVXC9QhxMl9Yfko2kx1OiYhDxhHs75RJZh\n' +
18+
'rNRxgfiwgSb50Gw4NAQaDIxr/DJPdLhgnpY6U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\n' +
50+
'mMUFlgDqFzcevjdGDce0QfboR+M7WDdm512Jz2SbRTgZD/4na42ThODOZz9z1AcM\n' +
51+
'zLgx2ZNZzVhBz0odCU4JVhOCEks/OzSyKeGwjIb4JAY7dh+Kju1+6MNfQJ4r1Hza\n' +
52+
'SVXH0+JlpJDaJ73NQ2JyfqELmJ1mTcptkA/N6rQWhlzycTBSlfogwf9xawgVPATP\n' +
53+
'4AuwgjHl12JI2HVVs1gu65Y3slvaHRCr0B4+Kg1GYNLLcbFcK+NEHrHmPxy9TnTh\n' +
54+
'Zwp1dsNQU+Xkylz8IUANWSLHYZOMtN2e5SKIdwTtl5C8YxveuY8YKb1gDExnMraT\n' +
55+
'VGXQDqPleug=\n' +
56+
'-----END CERTIFICATE-----'
57+
};
58+
59+
describe('MimeNode attachment fetch strict TLS', { timeout: 10000 }, () => {
60+
let server;
61+
let href;
62+
63+
beforeEach((t, done) => {
64+
server = https.createServer(httpsOptions, (req, res) => {
65+
res.writeHead(200, { 'Content-Type': 'text/plain' });
66+
res.end('Hello HTTPS attachment');
67+
});
68+
server.listen(0, () => {
69+
href = 'https://localhost:' + server.address().port;
70+
done();
71+
});
72+
});
73+
74+
afterEach((t, done) => {
75+
server.close(done);
76+
});
77+
78+
it('rejects a self-signed attachment host by default', (t, done) => {
79+
let mb = new MimeNode('text/plain').setContent({ href });
80+
81+
mb.build(err => {
82+
assert.ok(err, 'expected TLS error');
83+
done();
84+
});
85+
});
86+
87+
it('allows a self-signed attachment host when the attachment opts out', (t, done) => {
88+
let mb = new MimeNode('text/plain').setContent({
89+
href,
90+
tls: { rejectUnauthorized: false }
91+
});
92+
93+
mb.build((err, msg) => {
94+
assert.ok(!err);
95+
assert.ok(/Hello HTTPS attachment/.test(msg.toString()));
96+
done();
97+
});
98+
});
99+
});

0 commit comments

Comments
 (0)