To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it’s essential to make sure the server presents the right
certificate.
The certificate’s hostname-specific data should match the server hostname.
It’s not recommended to re-invent the wheel by implementing custom hostname verification.
TLS/SSL libraries provide built-in hostname verification functions that should be used.
Noncompliant Code Example
https built-in module:
let options = {
hostname: 'www.example.com',
port: 443,
path: '/',
method: 'GET',
secureProtocol: 'TLSv1_2_method',
checkServerIdentity: function() {} // Noncompliant: hostname is not verified
};
let req = https.request(options, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
}); // Noncompliant
tls built-in module:
let options = {
secureProtocol: 'TLSv1_2_method',
checkServerIdentity: function() {} // Noncompliant: hostname is not verified
};
let socket = tls.connect(443, "www.example.com", options, () => {
process.stdin.pipe(socket);
process.stdin.resume();
}); // Noncompliant
request module:
let socket = request.get({
url: 'https://www.example.com',
secureProtocol: 'TLSv1_2_method',
checkServerIdentity: function() {} // Noncompliant: hostname is not verified
});
Compliant Solution
https built-in module:
let options = {
hostname: 'www.example.com',
port: 443,
path: '/',
method: 'GET',
secureProtocol: 'TLSv1_2_method'
};
let req = https.request(options, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
}); // Compliant: default checkServerIdentity function is secure
tls built-in module:
let options = {
secureProtocol: 'TLSv1_2_method',
checkServerIdentity: (servername, peer) => {
if (servername !== "www.example.com") {
return new Error ('Error'); // Compliant: there is at least one check
}
}
};
let socket = tls.connect(443, "www.example.com", options, () => {
process.stdin.pipe(socket);
process.stdin.resume();
}); // Compliant
request module:
let socket = request.get({
url: 'https://www.example.com/',
secureProtocol: 'TLSv1_2_method' // Compliant
}); // Compliant: default checkServerIdentity function is secure
See