diff --git a/lib/_http_client.js b/lib/_http_client.js index b81ffa1cefc573..4a9d199ba398c7 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -36,6 +36,7 @@ const { StringPrototypeCharCodeAt, StringPrototypeIncludes, StringPrototypeIndexOf, + StringPrototypeStartsWith, StringPrototypeToUpperCase, Symbol, TypedArrayPrototypeSlice, @@ -270,6 +271,17 @@ function ClientRequest(input, options, cb) { if (host && !this.getHeader('host') && setHost) { let hostHeader = host; + let hostHeaderPort = port; + + // Prevent potential domain fronting misjudgement when using proxy + // Overwrite the default Host request header with the host of path + if (!StringPrototypeStartsWith(this.path, '/')) { + const proxyURL = new URL(RegExpPrototypeTest( + /^[^:]+:\/\//, this.path) ? this.path : `http://${this.path}`); + hostHeader = proxyURL.hostname; + hostHeaderPort = proxyURL.port || ( + proxyURL.protocol === 'https:' ? '443' : '80'); + } // For the Host header, ensure that IPv6 addresses are enclosed // in square brackets, as defined by URI formatting @@ -281,8 +293,8 @@ function ClientRequest(input, options, cb) { hostHeader = `[${hostHeader}]`; } - if (port && +port !== defaultPort) { - hostHeader += ':' + port; + if (hostHeaderPort && +hostHeaderPort !== defaultPort) { + hostHeader += ':' + hostHeaderPort; } this.setHeader('Host', hostHeader); } diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index b26cf7872f6582..6fd552a1e30cc2 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -61,7 +61,8 @@ const proxy = net.createServer((clientSocket) => { `CONNECT localhost:${server.address().port} ` + 'HTTP/1.1\r\n' + 'Proxy-Connections: keep-alive\r\n' + - `Host: localhost:${proxy.address().port}\r\n` + + // Match header Host with destination Host + `Host: localhost:${server.address().port}\r\n` + 'Connection: close\r\n\r\n'); console.log('PROXY: got CONNECT request');