Skip to content

Commit

Permalink
Handle ipv6 addresses in host-header correctly with TLS
Browse files Browse the repository at this point in the history
When a url uses an ipv6-addresses as the host part, the host-header of the request will be

[::1]:3000

(for ipv6 address ::1). To verify the IP address against a TLS certificate, we need to extract the
IP-address correctly.

Requires node with nodejs/node#14736 resolved to work.
  • Loading branch information
mattiasholmlund committed Mar 6, 2018
1 parent 226292c commit 0859a3d
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions lib/_http_agent.js
Expand Up @@ -196,13 +196,8 @@ Agent.prototype.addRequest = function addRequest(req, options, port/*legacy*/,
options = util._extend({}, options);
options = util._extend(options, this.options);

if (!options.servername) {
options.servername = options.host;
const hostHeader = req.getHeader('host');
if (hostHeader) {
options.servername = hostHeader.replace(/:.*$/, '');
}
}
if (!options.servername)
options.servername = calculateServerName(options, req);

var name = this.getName(options);
if (!this.sockets[name]) {
Expand Down Expand Up @@ -258,13 +253,8 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
options = util._extend({}, options);
options = util._extend(options, self.options);

if (!options.servername) {
options.servername = options.host;
const hostHeader = req.getHeader('host');
if (hostHeader) {
options.servername = hostHeader.replace(/:.*$/, '');
}
}
if (!options.servername)
options.servername = calculateServerName(options, req);

var name = self.getName(options);
options._agentKey = name;
Expand Down Expand Up @@ -342,6 +332,29 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
}
};

function calculateServerName(options, req) {
let servername = options.host;
const hostHeader = req.getHeader('host');
if (hostHeader) {
// abc => abc
// abc:123 => abc
// [::1] => ::1
// [::1]:123 => ::1
if (hostHeader.startsWith('[')) {
const index = hostHeader.indexOf(']');
if (index === -1) {
// Leading '[', but no ']'. Need to do something...
servername = hostHeader;
} else {
servername = hostHeader.substr(1, index - 1);
}
} else {
servername = hostHeader.split(':', 1)[0];
}
}
return servername;
}

Agent.prototype.removeSocket = function removeSocket(s, options) {
var name = this.getName(options);
debug('removeSocket', name, 'writable:', s.writable);
Expand Down

0 comments on commit 0859a3d

Please sign in to comment.